Using the GNU Debugger
25 Nov 2012Bundled with the GNU toolset is a full featured debugger in GDB. This blog post aims to be a cheatsheet to get yourself around this tool quickly.
The example program
Compile your code with debug info
You need to use the -g
switch with GCC in order to compile debug symbols. This helps the feedback that GDB will give you a great deal.
Loading your program into the debugger
So, in our example above the name of our executable would be “test”. So, we just tell gdb to load test by passing it in.
You can even start gdb with a text user interface, so I’ve just discovered.
It looks like this - not bad, eh?
Now we instruct gdb that we’d like to run the application
So you can see here that dividing by zero wasn’t the best career move for this program. But It nicely let us know that there was an arithmetic exception on line 9!
Examining data
To get just the call stack information, we issue the “backtrace” instruction
Examining data with print. We can view the value of variables by passing them to the print statement.
Print also supports printf style specifiers. Examining data at an address. We can view the value of data at a memory location by using the x
command.
Setting variables while attached is done with set
. We can stop the error in the program at runtime using this mixed with a breakpoint.
Working with breakpoints
To set a breakpoint in gdb, just pass the name of what you’d like to break on to the break
command.
You can set a breakpoint at a specific source code line number:
Finally, you can make a breakpoint using a combination of source code file name and line location:
View your existing breakpoints with info breakpoints
You can clear any set breakpoint with clear
.
You can step into code by issuing the step
command
You step over code by issuing next
. Its usage is the same as step
.
That’s all for now. As I come across other useful bits from GDB, I’ll certainly post them here. The items above have been lifesavers for me from time to time.