1. Preparations
We first write a piece of code for debugging, because gdb is a debugger, so it must be used in the debug version, and -g needs to be added when compiling the code.
Create a makefile
Write a piece of code for debugging
compile
2. Debugging
1. Enter and exit (q)
enter debug
exit debug
2. Display code (l)
But here it is not displayed from the first line. If we need, we can add a number after it to specify how many lines it starts to display.
You can see that it only displays 10 lines of code. If you want to see the complete code, you can continue l 1. Of course, since gdb will remember the last command, you can also press Enter directly.
Of course, you can also look at a certain function.
3. Run® and breakpoint (d)
run directly
Using r directly is one run, which obviously does not meet the purpose of debugging. We need breakpoints, the most commonly used is d+line number.
After breaking the breakpoint, Linux does not have a red dot like VS, so if we want to view the breakpoint, we need to use info b.
Num represents the number, End represents whether to open, Address is the address, and what is the breakpoint position.
Delete breakpoints (by number)
disable breakpoint
Open the breakpoint again
4. By process (n) and by statement (s)
In VS, we press F10 to step by process, and press F11 to step by statement. The difference between the two is that step by step will not enter the function, but step by step.
Put a breakpoint and start running
We use next(n) step by step, without entering the function.
We use steo(s) to enter the function statement by statement.
5. View variables and addresses
But this P has a disadvantage that it is only displayed once, and when the code continues to run, P must be used continuously. In order to display variables often, we can use display. It can refresh automatically.
Cancel display (by number)
6. Jump out of the loop (until) and directly end the function (finish)
There are 100 loops in the above function, obviously we cannot press n 100 times, in order to jump out directly, we can use until.
Now that we have entered the function, I want to get the result directly instead of pressing it step by step, so we can use finish to directly complete the current function.
7. From one breakpoint to another ©
In order to quickly find the location of the error code, we can have multiple breakpoints, and then run between the breakpoints, we can quickly determine which two breakpoints the code error is between.