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
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.
Breakpoints can be set using the
break command (shorthand:
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
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 (shorthand:
fin). 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
Change the value of a variable with the set foo = 10 command.
Show the stack with the
info stack command (shorthand:
i s). View stack frame #3 with the
frame 3 command.
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.
Temporarily disable a breakpoint with the
disable 1 command (shorthand:
Re-enable breakpoints with the
enable 1 command (shorthand:
clear command shorthand is
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 c ode
i key: move the cursor to the GDB view
↑ and ↓ keys: scroll through GDB command history