CS 3460 - Data Structures

Debugging with GDB


The gdb program provides an interactive debugging facility for source-level debugging and controlled execution of programs in a Unix environment. It can be used to debug programs written in any source language provided that the object file has been produced by a compiler that generates the appropriate information required by gdb. The debugging features provided by gdb include:

Using gdb

To use gdb, all object files must be compiled with the -g option and the link step must also include the -g option. For example, suppose the program consists of two files function.C and main.C. The compilation and link steps would be:


g++ -g -c function.C
g++ -g -c main.C
g++ -g main.o function.o -o main

Once an executable is created, it can be run under the control of gdb by invoking gdb with the command:

gdb main

Once in the debugger, you can type run (or r) and the program will execute to completion (or until the program aborts). Normally, you instead want the program to execute until you reach a particular statement number and then you want to step through the code statement by statement from there, examining values of variables as you go. For example, suppose I want to stop at some line in the main program, but I don't know which line. I type:

l main

and then type l again as needed in order to choose some line within the main at which I want execution to stop. I decide I want to stop execution at line 21. Next, I type:

b 21

to break at line 21 in the main. I then type:

r

and the program is executed up to line 21. I can then step through the program line by line by typing repetitively:

s

and I can examine contents of variables by typing:

p varname

where varname is the name of some variable.

Those are the basics of gdb. More gdb commands are listed below. You can also use gdb's help command and type man gdb at the Unix prompt for more information.

More Gdb commands

Many of the commands listed below can be abbreviated with one letter.