CS 24 GDB tutorial

Keegan McAllister and Sami Zerrade

April 14, 2008

Introduction

GDB is a debugger, a tool that allows you to interactively examine and manipulate a program as it runs. GDB supports many programming languages, including C and assembly.

Compiling

GDB requires the compiler or assembler to provide extra debugging information; this does not happen by default and must be enabled by a command-line option. For C programs, this is done by giving the -g flag when you execute GCC from the command line:
    [user@pong:~]> gcc -g -o foo foo.c
Since optimization tends to make debugging more difficult, you should avoid giving any of the optimization flags to GCC (-O1, -O2, etc.) If you are using the provided Makefile to compile your C project, the -g flag should be already specified; this is accomplished by the line
    CFLAGS=-Wall -g
in the Makefile.

For assembly language programs, there are two ways to invoke the assembler. You can invoke the assembler with GCC, in which case debugging is enabled the exact same way as for C. Alternatively, you can run the assembler directly, passing it the -g option, like this:

    [user@pong:~]> as -g -o foo foo.s
If you are using make to compile an assembly program, the Makefile must contain the line
    ASFLAGS=-g
to ensure that as is passed the debug option. (This line is missing from the Lab 2 Makefile; you can add it right after the CFLAGS line.)

Starting GDB

Invoke GDB by giving the executable you wish to debug as an argument:
    [user@pong:~]> gdb foo
After some startup messages you should get the GDB prompt:
    (gdb)
GDB accepts many commands (far more than you will need for CS 24). Documentation on all commands is available through the on-line help system which you can access with the command
    (gdb) help
What follows is a short listing of the commands we feel will be most useful for CS 24.

Running your program

Inspecting program state

Breakpoints

Other resources

In addition to this (brief) tutorial, there are many other GDB resources on the Web, including online manuals, a quick reference card, and other tutorials.