I recommend using CGDB instead of GDB, as it is helpful to see what is visually taking place. CGDB uses GDB behind the scenes and shows you the code as it is being executed.
-g compiler flag
. This is so the compiler and linker keep all the useful debugging information (symbol and code information).Launch GDB by telling it what program to debug: gdb myProgram
or cgdb myProgram
.
NOTE: You could run your program at this point, but it won't be useful for debugging. You'd want to set a breakpoint first.
run
command (shorthand: r
).quit
command (shorthand: q
).Breakpoints can be set using the break
command (shorthand: b
).
b 6
b foo
b foo.c:6
b 1
r
.By doing this you can step through your program one line at a time.
NOTE: A breakpoint stops execution before the line of code is executed.
Step into the current line with the step
command (shorthand: s
) when execution is paused.
For example, if execution is paused on the line x = foo();
, the command s
will enter foo()
and break at the first line of foo()
.
Step over the current line with the next
command (shorthand: n
). It will execute all the code until it reaches the next line in the current scope.
In the case of x = foo();
, all of foo()
will be executed and its returned value will be assigned to x
. Execution will then pause on the line that comes after x = foo();
.
Step out of a function with the finish
command. It will finish the current function and pauses execution once the function is completed.
Complete execution of a loop from the last line of the loop using the until
command and execution will resume on the line below it.
Resume normal execution with the continue
command (shorthand: c
); it'll stop at the next breakpoint.
View the value of a variable (when execution is paused) with the print foo
command (shorthand: p foo
). You can even view the result of an expression, such as p listContainsFoo()
.
Change the value of a variable with the set foo = 10 command.
Show the stack with the info stack
command (shorthand: i s
).
Conditional breakpoints are used to pause execution only if some condition is met.
You can create them with expressions.
For example, b 6 if x == 0
or b 6 if listContainsFoo()
.
See the list of current breakpoints with the info breakpoints
command (shorthand: i b
).
NOTE: Each breakpoint is given a number.
delete 1
(shorthand: d 1
)clear foo.c:6
(shorthand: cl foo.c:6
)Temporarily disable a breakpoint with the disable 1
command (shorthand: dis 1
).
Re-enable breakpoints with the enable 1
command (shorthand: en 1
).
CAUTION: The clear
command shorthand is cl
. The continue
command shorthand is c
. You do not want to mix up these two.
If you are using CGDB know these shorthand commands:
Escape key: move cursor to source code view
↑ and ↓ keys: scroll through the code
i key: move the cursor to the GDB view
↑ and ↓ keys: scroll through GDB command history
Written by Chris Blume
Edited by Morgan Landis