Debugging is extremely important to determine bugs in your program. gdb is a powerful debugger that is used to debug programs with the gcc compiler. Can run your program, stop at predetermined locations (breakpoints), display/set variables, trace program's execution, execute one line at a time, etc.
To allow gdb to work with your program, you should use the option -g when compiling your program.
> gcc -g program.c -o program
> gdb program // runs gdb
(gdb) run
Runs the program, stopping to show any error it encounters and the line it encounters. [show example]
When execution stops, you can use list to see the source code around the line where the program crashed.
print can be used to print out values (variables, pointers, arrays, etc.)
(gdb) list 9 // list 5 lines before line 9 and 4 lines after (gdb) list 9, 13 // list lines 9 through 13 (gdb) print i // prints the variable i. looks for local variable first, then external (gdb) print main::i // prints the variable i inside the function main
Breakpoint allows the program to pause execution at a certain point.Examples:
(gdb) break 12 // sets a breakpoint at line 12 (gdb) break main // sets a breakpoint at the beginning of main (useful when you dont know the line number)
After setting a breakpoint, we can step through the program. This allows us to step through the program line-by-line. Keyword: "step" or just "s"
(after breakpoint reached) (gdb) step (gdb) s // alternative (gdb) s 3 // steps through 3 lines of code
NOTE: "step" steps through one line of code, and one line of code may have multiple C statements.
(gdb) info break // lists all the breakpoints (gdb) clear // deletes breakpoint at next instruction to be executed (gdb) clear 12 // deletes breakpoint at line 12 (gdb) clear main // deletes breakpoint at entry of main (replace main with any function)
Variables can be modified in gdb.
(gdb) set var i=5 // sets the variable i to 5 (gdb) set var i=i+5 // use any expression (gdb) set var main::i=0 // set the i inside main
Sometimes you need to look at the hierarchy of function calls. If you want to look at the call stack you need to do:
(gdb) backtrace (gdb) bt
gdb can be used within emacs and is well-integrated. First you have to make sure that the program is compiled properly using the -g option as previously mentioned.
To start gdb within emacs, type in:
M-x gdb [Alt-x gdb]
This will gdb in the same window by splitting it, showing the gdb prompt and the source code at the same time. This provides visual feedback regarding which line gdb is currently running (or stopped at), the breakpoints, etc.
NOTE: Very useful list of emacs commands.