10.2 Using gdb to debug your program

To use gdb to debug your program, you can start the debugger, and give it as an option the full name of your program:

gdb hello

Or, under dos:

gdb hello.exe

This starts the debugger, and the debugger immediately loads your program into memory, but it does not run the program yet. Instead, you are presented with the following (more or less) message, followed by the gdb prompt ’(gdb)’:

GNU gdb 6.6.50.20070726-cvs
Copyright (C) 2007 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-suse-linux".
(gdb)

The actual prompt will vary depending on your operating system and installed version of gdb, of course.

To start the program you can use the run command. You can optionally specify command line parameters, which will then be fed to your program, for example:

(gdb) run -option -anotheroption needed_argument

If your program runs without problems, gdb will inform you of this, and return the exit code of your program. If the exit code was zero, then the message ’Program exited normally’ is displayed.

If something went wrong (a segmentation fault or such), gdb will stop the execution of your program, and inform you of this with an appropriate message. You can then use the other gdb commands to see what happened. Alternatively, you can instruct gdb to stop at a certain point in your program, with the break command.

Here is a short list of gdb commands, which you are likely to need when debugging your program:

quit 

Exit the debugger.

kill 

Stop a running program.

help 

Give help on all gdb commands.

file 

Load a new program into the debugger.

directory 

Add a new directory to the search path for source files.

Remark My copy of gdb needs ’.’ to be added explicitly to the search path, otherwise it doesn’t find the sources.

list 

List the program sources in chunks of 10 lines. As an option you can specify a line number or function name.

break 

Set a breakpoint at a specified line or function.

awatch 

Set a watch-point for an expression. A watch-point stops execution of your program whenever the value of an expression is either read or written.

In appendix C.14.3 a sample init file for gdb is presented. It produces good results when debugging Free Pascal programs.

For more information, refer to the gdb User Manual, or use the ’help’ function in gdb.

The text mode IDE and Lazarus both use GDB as a debugging backend. It may be preferable to use that, as they hide much of the details of the debugger in an easy-to-use user interface.