Introduction to Using GDB Under Emacs

For most users, the graphical debugging interface presented by ddd is the best way to debug programs. However, hard-core emacs users may prefer the gdb interface provided by that editor. (One advantage of the emacs interface is that it is available essentially everywhere, whereas ddd might not be available on many machines.)

These instructions are written using the "conventional" emacs notation: C-x means "hold down the control key and type x", M-x means either "hold down the meta key and type x" or "type the ESC key followed by x" (the two are usually equivalent). SPC is the space bar, and ESC refers to the Escape or Esc key (usually the upper-left-key on the keyboard), while RET is the Return or Enter key on your main keyboard; there is no guarantee whether the Enter key on the numeric keypad will produce the same result. Finally, [f1] refers to function key 1 along the top row of your keyboard (and so forth).

Case matters: M-X is not the same as M-x.

Emacs Windows

Before you can use gdb effectively, you must become familiar with emacs windows. Most window commands start with C-x 4. For example, C-x 4 f will split the screen in half and open a new file in the other window. C-x 4 b will select an already-opened file (buffer) in the other window. These are the two that I use most often; you can also type C-x 4 [f1] (function key 1) to get a full list of window commands.

There are also three useful window commands that don't start with C-x 4. These are: C-x o (oh) to switch to the other window, C-x 0 (zero) to delete the current window and go back to one-window mode, and C-x 1 to delete the other window and go back to one-window mode. If you use the menu bar, C-x 1 is available under the Files menu. You can also change to a different window by simply clicking with the mouse.

GDB Mode

Once you've mastered the window commands, the gdb mode is very simple. Start gdb by typing M-x gdb RET. It will prompt you Run gdb (like this): gdb. Type in the name of your executable and hit RET. You will then find yourself at a gdb command prompt, where you can set breakpoints, run the program, etc. M-p invokes a command history to save typing.

When you hit a breakpoint, emacs will automatically bring up the source code in the other window. If you step through the code, the little arrow will follow the source code.

The other really handy thing is that if you place the cursor on a source code line (e.g., you use C-x o or C-x 4 f to enter the other window and then navigate to an interesting place in your code), you can type C-x SPC (the space bar), and emacs will set a breakpoint at that line of code. That saves me a lot of time, because I never have to concern myself with line numbers.


© 2001, Geoff Kuenning

This page is maintained by Geoff Kuenning.