Video Tutorial
Gdb commands
Starting gdb
gdb meu_programa
Don't forget to compile the program with the -g option (and without optimization options like -O3)
Running the program on gdb
run
Without placing a breakpoint, the program will run until the end. So, in general, we put some breakpoint, even if it is in the main function.
But if you have a segmentation fault in your program, you can run without a breakpoint and find out which line has a problem.
breakpoints
Breakpoints are places (lines or functions) where you want the program to stop executing and wait for your command (to print variables, to execute one line at a time, etc.).
Creating Breakpoints
You can place a breakpoint on a function and execution will always stop when the function is called. Example:
break main
In this case, the program stops right at the start of execution.
You can also place breakpoints on lines of your code. Example:
break 10
In this case, the program stops when it reaches line 10.
When you have multiple files (we'll see that in the course), you need to specify which file you want the line to be from. Example:
break exemplo.c:10
In this case, the program stops when it reaches line 10 of the example.c file.
Clearing breakpoints
When a breakpoint is created, it gets a number. You can delete a breakpoint using its number. Example:
delete 3
You can also delete all breakpoints with the command:
clear
Running step-by-step
The idea of the debbugger (or debugger, in Portuguese) is to allow you to run the program step-by-step, following its execution, while also being able to see or change the value of variables, call functions, etc.
When gdb stops at a breakpoint, you can speak to continue the execution using the command:
continue
In that case it will stop at the next breakpoint it finds.
If you want to run one command at a time, you have two options:
step
next
Both go to the next command, but the next
always goes to the next line in the file, while the step
enter any function that is called on that line.
For example, imagine that you have the following lines in your code:
y = f(x)
w = g(k)
and that gdb stopped at the line where y = f(x)
.
If you give the command next
, gdb will go to the next line (w = g(k)
), but if you give the command step
, it will go to the first line of the function f
.
Printing variables
You can print the value of any variable x using
print x
You can also print struct fields, vector positions, etc.
If you replace print
by display
, then that variable will always be visible and you can track changes in its value.
To remove something that is display
, do it
undisplay n
where n
is the number of the display you want to remove.