Debugging with GDB (September 2007)

Chapter 19: Using GDB under gnu Emacs 255
19 Using GDB under gnu Emacs
A special interface allows you to use gnu Emacs to view (and edit) the source files for
the program you are debugging with GDB.
To use this interface, use the command M-x gdb in Emacs. Give the executable file you
want to debug as an argument. This command starts GDB as a subprocess of Emacs, with
input and output through a newly created Emacs buffer.
Using GDB under Emacs is just like using GDB normally except for two things:
All “terminal” input and output goes through the Emacs buffer.
This applies both to GDB commands and their output, and to the input and output
done by the program you are debugging.
This is useful bec ause it means that you can copy the text of previous commands and
input them again; you can even use parts of the output in this way.
All the facilities of Emacs’ Shell mode are available for interacting with your program.
In particular, you can send signals the usual way—for example, C-c C-c for an interrupt,
C-c C-z for a stop.
GDB displays source code through Emacs.
Each time GDB displays a stack frame, Emacs automatically finds the source file for
that frame and puts an arrow (‘=>’) at the left margin of the current line. Emacs uses a
separate buffer for source display, and splits the screen to show both your GDB session and
the source.
Explicit GDB list or search commands still produce output as usual, but you probably
have no reason to use them from Emacs.
Warning: If the directory where your program resides is not your current di-
rectory, it can be easy to confuse Emacs about the location of the source files,
in which case the auxiliary display buffer does not appear to show your source.
GDB can find programs by searching your environment’s PATH variable, so the
GDB input and output session proceeds normally; but Emacs does not get
enough information back from GDB to locate the source files in this situation.
To avoid this problem, either start GDB mode from the directory where your
program resides, or specify an absolute file name when prompted for the M-x
gdb argument.
A similar confusion can result if you use the GDB file command to sw itch to
debugging a program in some other location, from an existing GDB buffer in
Emacs.
By default, M-x gdb calls the program called gdb’. If you need to call GDB by a different
name (for example, if you keep several configurations around, with different names) you can
set the Emacs variable gdb-command-name; for example,
(setq gdb-command-name "mygdb")
(preceded by M-: or ESC :, or typed in the *scratch* buffer, or in your .emacs file) makes
Emacs call the program named mygdb instead.
In the GDB I/O buffer, you can use these special Emac s commands in addition to the
standard Shell mode commands: