Department of
Computer & Electrical Engineering & Computer Science
California State University, Bakersfield

GDB BASICS

GDB Basics - GNU Debugger

Compile each course code file using -g. Without the -g flag, the compiled binary may have insufficient information to assist GDB in debugging the progrma. Older documents from the department may recommend the -gstabs+ flag but this is no longer standard.

A SAMPLE GDB SESSION

  • Run the executable a.out through the debugger: gdb a.out
  • Setting a breakpoint follows the format break <POINT>, where <POINT> is a named function, or label in your code. Examples:
    • Set a break point in the program, such as at main() execute: break main
    • Set a break point in the calculate method of Time class: break 'Time::calculate' (hit TAB to view choices).
    • Set a break point in the copy constructor of the List template class: break List<int>::List(const List<int> &).
    • Set a break point at line 7: break 7
    • Break on line 7 if condition met: break 7 if (num == 1)
    • Assuming, before compiling, you created an arbitrary breakpoint in your C-code not associated with a fuction:
      int main() {
          ...
      _apples:
          i++;
          ...
      	
      Set a breakpoint with: break _apples
  • Generally, after setting a breakpoint the next step is to run the program: run
  • However, if you intended to provide command line arguments, they are executed with run as: run arg1 arg2
  • When the program has stopped at a breakpoint, you have several options:
    • Execute the next source line without stepping into called functions: next
    • Force return from current function: return
    • List code starting at 5 lines before and after line 20: list 20
    • List code from line 20 to line 30: list 20,30
    • Continue until current function returns: finish
    • Display value of variables: print i
    • Display the value of a dereferenced pointer: print *ptr
    • Examine memory at address 0xF087A: x/d 0xF087A
    • Get help on examine command: help x
    • Assign variables: print num = 3
    • Step through your program line by line: step
    • Step through your program 5 lines: step 5
    • View the type of a variable or class object: whatis i
    • View current breakpoints: info breakpoints
    • View stack trace of current active functions: info stack, bt or backtrace
    • Continue with execution: continue
    • Delete the first break point set: delete 1
    • Exit gdb: quit

NOTE: Commands can be shortened to their smallest set of unique characters; e.g. print can be replaced by p; step can be replaced by s.