Debugging C++ with gdb

There are two kinds of errors that you will encounter as you develop projects in C++. The problem of how to resolve the logic error remains. You could guess where in your program the error occurred and put in some cout statements there to print out the value of variables to see what was happening. Sometimes this works but then you're left with having to delete all the cout statements and hope that you don't accidentally take out some good code while you're doing it.

A better solution is to use a debugger program so that you can control how your program is running. Here are some of the basic actions you want to perform:

Running the gdb Debugger

Before you can use gdb on a program, you must prepare your program for debugging with gdb. You must compile it with the -g or -ggdb option. The -g option creates additional information about the program and deposits it in a symbol table. (The -ggdb option creates more information of this type.) The debugger must have this symbol table to do its work. The general syntax is:
        g++ -g filename.cpp -o executable_file
Start gdb by typing in the following command:
        gdb executable_file
where executable_file is the executable version of the program. Remember: if you do not use the -o option when you compile a program, the executable file will be called a.out.

The system prompt changes to the gdb prompt, and you are ready to start entering gdb commands. There are many commands available but the following table shows some of the basic ones.

GDB Command Summary

Command Action
help Display information about gdb commands.
run Start running the program under gdb.
print expression Display the contents of a variable or expression.
break function Set a breakpoint at the designated function.
clear function Clear the breakpoint set at the designated function.
delete [number] Delete all breakpoints if no number is specified, or deletes just the breakpoint specified by number.
info breakpoints Display the number of each breakpoint.
step Execute just the next line of code.
next Execute just the next line of code but skip over any function calls in the line.
list Display lines of source code.
quit Exit gdb.

As is the case with most debuggers, the best way to learn gdb is to actually use it on a program. There is an simple program you can use to do this in the lab exercise. Here is a list of the references for using gdb:

On Hercules Use dbx

If you would like to learn the debugger on Hercules, please click here