Overview
GDB is a tool commonly used by embedded software engineers for debugging. This article provides a brief summary of GDB and its common commands.
What is GDB?
GDB, also known as the GNU debugger, is a tool used to help debug programs.
Basic features
GDB provides several basic capabilities:
- Set breakpoints in a program.
- When the program stops at a breakpoint, inspect all variables and register values.
- When stopped at a breakpoint, change variable or register values without modifying the source code.
GDB command summary
Before learning to use GDB to debug programs, here is a list of common GDB commands.
| Command | Description |
| r | run: start execution and stop at the first breakpoint; if no breakpoint is set, run the program |
| b fun | set a breakpoint at the beginning of function "fun" |
| b N | set a breakpoint at line N in the current source file |
| b file.c:N | set a breakpoint at line N in file.c |
| d N | delete breakpoint number N |
| info break | display information about all breakpoints |
| c | continue execution until the next breakpoint or program end |
| f | finish: run until the current function returns |
| s | step one line, entering function calls |
| s N | step the next N lines |
| n | next one line; unlike s, do not enter function calls |
| p var | print the value of variable "var" |
| set var=val | set the value of variable "var" |
| bt | print the call stack (backtrace) |
| q | quit gdb |
Using GDB
GDB can be used in two main scenarios:
- Debug programs that crash or have logical errors.
- Analyze a core dump generated when a program crashes.
Typical workflow:
Compile and build the program with debugging symbols enabled, for example:
gcc -g main.cpp -o test.out
Start GDB with the executable:
gdb test.out
Use GDB commands to analyze and debug the program.
Exit GDB when finished.
Example
//main.c#include <stdio.h>int main(){ int balance=100; int target=1000; float rate = 0.1; int year = 0; do { float interest = balance * rate; balance = balance + interest; year++; } while ( balance >= target ); printf("%d No. of years to achieve target balance.", year); return 0;}
Step 1: Compile with debugging information:
gcc -g main.c -o test.out
Step 2: Start GDB:
gdb test.out
Step 3: Set a breakpoint at the entry of main:
b main
Step 4: Run the program:
run
Step 5: Use step to advance to line 13:
s
Step 6: Inspect variables balance, rate, and interest:
p balance p rate p interest
Step 7: Use step to advance to line 15.
Step 8: Inspect balance, rate, and interest again. If no loop is observed, the while condition is incorrect; it should be balance < target.
ALLPCB