You can debug C in Emacs using GDB.
Setup
- Write your program.
Compile using the -g option: For example, M-x compile then gcc -g -o a.out file.c. (In real life, you should probably use a MakeFile with a debug target)
Run gdb: M-x gdb. This should split the screen between your code and the gdb interactive prompt.
Set some breakpoints with C-x SPACE. You should see them appear in an extra left fringe.
Run your program with r. If you have command line arguments, put them after r, like r foo bar.
- Once GDB hits a breakpoint, you should see a black triangle in the left fringe. you can step forward in your code and see what values your variables take on. See below for a short list of commands.
Commands
s : step. Execute the next line of code.
n : next. Execute the next line of code in this function. If the next line of execution would be a function call, the whole function is run and the result returned before you stop again.
p : print. Print the value of some variable.
fin : finish function. Run until the end of the current function, then resume single-stepping.
c : continue. Run until the debugger hits a breakpoint.
Of course, before you use a debugger, find out if there's a simpler way to find out what's going wrong. One way to do this is with print statements, either to stdout or to a log file. Automated use of print at function call boundaries is extremely useful in other languages I've used like Python and Scheme, so there is probably a way to do it in C as well.
Right now, the instructions on this page are stolen from http://tedlab.mit.edu/~dr/gdbintro.html. They were tested on Aquamacs 1.3 with GDB i386-apple-darwin, so your results may vary.
Other Commands
clear n : clear breakpoint at line n.
Here is the table of contents of the official GDB manual.
Note on fringes: I suspect that almost all of these instructions will work on any emacs except for the fringe display. Terminal-based emacsen usually find a different way to display things, so there will probably be some visual feedback.
See also: Debug Python in Emacs
Next in this exciting series: Debug C++ in Emacs !
Note: GDB is able to debug Objective C, Fortran, Ada, Pascal and Modula-2 in addition to C and C++. You are welcome to try GDB with these languages and write up the differences on the wiki.
