Home / Tutorials / GDB step-by-step debugging
GDB step-by-step debugging
GDB (the GNU Debugger) is the standard debugger for C and C++ programs on Linux. This tutorial walks through the most useful commands with a concrete example.
All code for this tutorial is on GitHub: github.com/achint/gdb-tutorial
Compiling for debugging
You must compile with the -g flag to include debug symbols. Without it, GDB can't map machine instructions back to your source lines.
gcc -g -o myprogram myprogram.c
For a release build without debug info:
gcc -O2 -o myprogram myprogram.c
Starting GDB
gdb ./myprogram
You're now in the GDB shell. Type run (or r) to start the program.
Setting breakpoints
(gdb) break main # break at the start of main()
(gdb) break myfile.c:42 # break at line 42 of myfile.c
(gdb) break my_function # break at the start of a function
Stepping through code
| Command | Short | What it does |
|---|---|---|
next |
n |
Execute the next line (steps over function calls) |
step |
s |
Step into function calls |
continue |
c |
Run until the next breakpoint |
finish |
fin |
Run until the current function returns |
Inspecting variables
(gdb) print my_variable # print the value of a variable
(gdb) print *my_pointer # dereference and print a pointer
(gdb) info locals # print all local variables
(gdb) info args # print all function arguments
Reading the stack
(gdb) backtrace # show the call stack
(gdb) frame 2 # switch to frame 2
(gdb) info frame # details about the current frame
Watchpoints
Watchpoints pause execution whenever a variable's value changes — useful for tracking down unexpected mutations.
(gdb) watch my_variable # pause when my_variable changes
(gdb) rwatch my_variable # pause when my_variable is read