GNU Debugger (GDB)
The GNU Project Debugger (GDB)
Installation
Windows
On Windows, gdb is a part of MinGW. See MinGW for more information.
Ubuntu
GDB comes installed by default on most Unix-like systems, but if it's not installed, you can run the following:
sudo apt install gdb
Usage
This section defines simple usage of GDB. It is by no means comprehensive, but it should be sufficient for a fair amount of debugging scenarios.
- Compile
You would compile your file as per usual, but attach the g flag:$ cc -g main.c
- Launch To launch gdb, run the following, where "a.out" is the output of the compile command above
- Configure Debug See below for useful debugging commands such as adding breakpoints, stepping through functions or printing the values of variables
- Run Run the program with your added breakpoints by typing the "run" command.
- Finish To close gdb, you can enter "q"
GDB Commands
Some useful gdb commands include:
General | |
---|---|
help | Shows details about commands |
Controlling Execution flow | |
break <line_number> | Adds a breakpoint at the given line number. Other options include break <file_name:line_number> |
run | Executes the program in gdb |
next | Debugger will execute the next line as single instruction. This includes whole functions Can be abbreviated to n. |
step | Runs a single line of code. Will enter into a called function, unlike next.
Can be abbreviated to s. |
continue | Continues execution until the next breakpoint.
Can be abbreviated to c. |
finish | If you're in a function which returns at some point, you can use the finish command to execute the program until the end of the function.
It's equivalent to setting a breakpoint at the return line of a function, and then letting the program run. |
Gathering information | |
print <variable> | prints the value of a specified variable.
Can be abbreviated to p. |
info variables | Will give information on all variables, including some that you haven't defined |
info locals | Will give information on variables in the current scope |
info args | Will return information on the arguments passed |
Dealing with Pointers | |
print *<pointer> | Prints what the pointer is pointing to |
print &<variable> | Displays the address of the variable |
gdb for openOCD
See the openOCD page for more details on using it. Here are some additional gdb commands that might be useful when debugging on hardware:
monitor <command> | [asses <command> directly to openOCD. Allows openOCD commands to be passed through gdb |
info registers | prints the names and values of the CPU registers |
info registers rX | Prints the value of the specifed register rX, where X is a number of a register (0-15 in ARM). |
set $rX=val | sets register X (O-15 in ARM) to the value val |
x/format address | Reads the contents of address and displays it according to format.
See this link for more. |