You can debug C in Emacs using GDB.

Setup

  1. Write your program.
  2. 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)

  3. Run gdb: M-x gdb. This should split the screen between your code and the gdb interactive prompt.

  4. Set some breakpoints with C-x SPACE. You should see them appear in an extra left fringe.

  5. Run your program with r. If you have command line arguments, put them after r, like r foo bar.

  6. 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

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

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.

Debug C in Emacs (last edited 2008-08-04 17:55:58 by c-98-212-25-97)