Debug with GDB
First steps:
- Compile with proper flags:
-g
- (Optional) Turn off code optimization:
-O0
Debugging
- Run gdb with the program not passing its arguments in this step:
gdb ./example
- After executing gdb, you can start the program with run command (with any needed arguments)
- You can run the gdb with the
-tui
flag to see the code while debugging.
Command | Short | Description |
---|---|---|
run | r | Start the executable from the start |
list | l | List code lines where the execution is |
quit | q | or Ctrl-D, gdb exits |
Ctrl-C | While running, hit Ctrl-C stops the execution and gdb shows where the program was | |
frame | f | Print the current line |
backtrace | ba | Print the function call stack |
continue | c | Continue execution |
down | do | Go to the called function |
up | up | Go the calling function |
info locals | Print all local variables in the current scope | |
print var | p var | Print variable’s value |
display var | disp var | Print the variable’s value at every prompt |
set var | set var | Change the variable’s value |
watch var | wa var | Stops if the variable’s value changes |
break line | br | Insert breakpoints into the code, you can pass filename or function name as well |
delete | d | Unset a breakpoint |
condition | cond | Breaks if a condition is met |
disable | dis | Disable a breakpoint |
enable | en | Enable a breakpoint |
info breakpoints | info b | List all breakpoints |
tbreak | tb | Temporary breakpoint |
next | n | Continue until next line |
step | s | Step into function |
finish | fin | Continue until the function’s end |
until | unt | Continue until line/function |
help | h | Print description of a command |
info threads | List all running/waiting threads from the process | |
thread id | Switch execution to a specific thread id | |
br line thread id | Set a breakpoint in a specific thread | |
thread apply 1 br line | Set a breakpoint in line line of the thread 1 | |
thread apply all bt | Print the backtrace of all threads |
- 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>