Skip to content

Using gdb

marksvc edited this page Jun 18, 2021 · 1 revision

gdb is the GNU debugger and can be invaluble in dissecting C/C++ programs

Running gdb

To start gdb, use this at the command line:

 gdb ''program-name''

To run the program, use this inside gdb:

 r ''args''

It's also possible to specify all the arguments on the command line (giving the benefit of tab completion and filename globbing):

 gdb --args ''program-name arg1 arg2 ...''

After starting gdb like this, use the r command with no arguments:

 r

gdb will then use the arguments passed on the command line.

If you have an existing test command (in a script or Makefile) you can run it under gdb control by prepending gdb --args to it. In a Makefile, you can create an empty variable called GDB and use it in front of the test command:

 check:
     $(GDB) ''program-name arg1 arg2''

Running

 make GDB="gdb --args"

will now test the program under the control of gdb.

Favorite commands

There are many commands available within gdb. These can be discovered by using help within the program, the manual page in linux, or a reference card. The following are my favorites:

 c Continue running
 b ''file'':''line'' Set breakpoint
 catch throw Stop when exception is thrown
 catch __cxa_throw Same again, can be more reliable
 clear Clear current breakpoint
 bt Show stack
 up ''n'' Go up stack trace
 info local
 info args
 p ''expr''
 q Quit!
Clone this wiki locally