Home | Projects | Notes > Unix/Linux > GDB Cheat Sheet

GDB Cheat Sheet

 

GNU Debugger (GDB) Cheat Sheet

-g option embeds symbolic debug information into the output file program. This debug info includes:

  • Function names

  • Variable names and types

  • Line numbers in source code

  • Mapping between binary instructions and source code

CommandDescription
break <location> or
b <location>
Set a breakpoint (e.g., b main, b 11, b file.cpp:25, b func).
run or rStart the program from the beginning.
deleteDelete all breakpoints. Use delete <n> to remove a specific one.
disable <n> / enable <n>Disable or enable a breakpoint.
info breakpoints or i bList current breakpoints and their status.
next or nExecute the next line (step over function calls).
step or sStep into the function call on the current line.
finishRun until the current function returns.
continue or cResume execution after a breakpoint.
print <expr> or p <expr>Print the value of an expression or variable.
display <expr>Auto-print the value of an expression each time the program stops.
undisplay <n>Remove a display expression.
backtrace or btShow call stack (current function and callers).
frame <n>Switch to frame number n in the call stack.
up / downMove one frame up or down (in terms of stack number where #0 being the top frame) the stack.
info localsShow local variables in the current frame.
info argsShow function arguments in the current frame.
list or lShow source code near the current line or a specific location.
set var <var>=<value>Change the value of a variable.
watch <expr>Set a watchpoint (pause when the expression changes).
info watchpointsList watchpoints.
stepi or siStep one machine instruction.
nexti or niStep over one machine instruction.
quit or qExit GDB.

 

Sample Program to Practice GDB

Source (gdb.cpp)

Compile the program:

Attach GDB:

Set breakpoints:

View breakpoints:

Run the program:

Continue to the next breakpoint:

View call stack:

#n refers to each stack frame number.

View local variables:

View the value of a local variable in a different stack frame:

First, you need to go to the stack frame in which the variable you want to print is declared.

View the source code near the current line:

View the current line:

Return to the top stack frame:

Run until the current function returns: