Most IDEs come with a built-in debugger. However, for most skilled C programmers, there is only one debugger: gdb.
The Gnu De-Bugger (GDB)
Perhaps the most powerful command-line tool available to the common programmer, gdb is an industry standard for debugging C code.
While learning all the intricacies of gdb could take lifetimes, there are several features that are indispensable:
- BREAKPOINTS – This is the ability to stop program execution on particular lines of code
- SYMBOL PRINTING – This is the ability to look at variables in your code while it’s running
- SYMBOL MODIFICATION – This is the ability to change the variables in your code while it’s still running
- STEP INTO – This is the ability to go inside of functions and walk through those internal operations
However, while gdb is both powerful and ubiquitous in the industry, it is very poorly documented. This is the one time I’ll discourage reading the manual pages. If you want to know more about gdb, because you need some feature that I’ve not depicted, go to Google or Stack Exchange.
Note: If you want to debug a program, you must compile it with the -g tag. See the sample makefile for an excellent example.
Before we launch directly into GDB, we should look at some common commands and how we employ them.
First, we have to consider how we call gdb. If your program takes no arguments, it’s as simple as this:
However, most of our command-line code will take at least one additional argument. For that, we have to use the –args tag (with two – signs), which reads a chain of arguments like it was the terminal. For example, if we called panda with arguments ‘5’ and ‘Hello, world’, it would look like this:
gdb –args ./panda 5 “Hello, world”
So now you’re running the debugger. The debugger’s primary feature is the breakpoint, which stops the program at a given point so that we can start exploring. If you want to set a breakpoint in the source line_number.c, you use the following syntax at the command line:
This tells the debugger to stop operation at line 55 of the source file line_number.c
Then, you run the debugger with the simple command:
The program will run as normal until it reaches its breakpoint. We then have a few options:
- We can step into the function on that line using the command:
- We can go past the function on that line using the command:
- We can look at a variable using the command:
- print variable_name
- We can change the value of a variable using the command:
- set variable_name = new_value
- We can let the program proceed as normal using the command:
- Or, we can kill the program using the command:
That’s about all you need to know to accomplish great things with the debugger. However, it’s important to know how to close gdb. The command we use to close gdb is:
Note: If the program you’re debugging is still set up in the debugger, it will ask you if you want to kill it. Since you can’t quit while the program is running, just tell gdb “yes” when the prompt appears.