Debug with GDB

1 minute read

First steps:

  1. Compile with proper flags: -g
  2. (Optional) Turn off code optimization: -O0


  1. Run gdb with the program not passing its arguments in this step: gdb ./example
  2. After executing gdb, you can start the program with run command (with any needed arguments)
  3. You can run the gdb with the -tui flag to see the code while debugging.
runrStart the executable from the start
listlList code lines where the execution is
quitqor Ctrl-D, gdb exits
Ctrl-C While running, hit Ctrl-C stops the execution and gdb shows where the program was
framefPrint the current line
backtracebaPrint the function call stack
continuecContinue execution
downdoGo to the called function
upupGo the calling function
print varp varPrint variable’s value
display vardisp varPrint the variable’s value at every prompt
set varset varChange the variable’s value
watch varwa varStops if the variable’s value changes
break linebrInsert breakpoints into the code, you can pass filename or function name as well
deletedUnset a breakpoint
conditioncondBreaks if a condition is met
disabledisDisable a breakpoint
enableenEnable a breakpoint
info breakpointsinfo bList all breakpoints
tbreaktbTemporary breakpoint
nextnContinue until next line
stepsStep into function
finishfinContinue until the function’s end
untiluntContinue until line/function
helphPrint description of a command
  • Take a look at the GDB cheatsheet here.

Debugging MPI applications with GDB

If you have xserver running (use VCXSRV or Xming on windows for ssh), compile your code with -g and debug it with:

mpirun -np 2 xterm -e gdb <application>

More information at OpenMPI FAQ.

Inspecting the core file

If the program crashes with Segmentation fault message, it is sometimes helpful to increase the maximum core file size to save the in-memory state of the program at the time it crashes.

$ ./example
Segmentation fault
$ ulimit -c 2048
$ ./example
Segmentation fault (core dumped)
$ gdb ./example <corefile>