Linux system: ubuntu-20.04
Introduction to gdb
The full name of gdb is "GNU symbolic debugger". It is easy to see from the name that it was born in the GNU project (also born at the same time as GCC, Emacs, etc.) and is a commonly used program debugger under Linux. Since its development, GDB has iterated many versions. The current GDB supports debugging programs written in multiple programming languages, including C, C++, Go, Objective-C, OpenCL, Ada, etc. In actual scenarios, GDB is more commonly used to debug C and C++ programs. Generally speaking, gdb mainly helps us complete the following four functions:
- Start your program and run it as you like according to your customized requirements.
- Pause a program at a specified place or condition.
- When the program is stopped, you can examine what is happening in your program at that time.
- Modify variables or conditions in the program during program execution to correct the impact of one bug to test other bugs.
- 1. gdb installation
sudo apt-get install gdb
- 2. Write routines
#include"stdio.h"
void func()
{
int i=0;
for(i=0;i<5;i++)
{
printf("%d\n",i);
}
}
int main()
{
func();
return 0;
}
Compilation runs normally.
- 3. Perform gdb debugging
. Next, debug. You mustgcc test1.c
add -g after compilation to indicate that you need to perform gdb debugging on this file, and thengdb a.out
enter the gdb debugging mode, as follows:
①Enter " r
" to indicate run to run the program
②Enter " l
" to indicate list to view the source program.
Due to the character limit, if you can't see it completely at one time, please try it several times .
③ Enter " b 14
" to indicate the break point on line 14
④ Enter " s
" to indicate step to enter the breakpoint
⑤ Enter " n
" to indicate next to enter the next statement
⑥ Enter " p i
" to indicate printf to print the value of variable i at this time
⑥You can use shell to call terminal commands in gdb, for example, enter " shell cat test1.c
" to view the file content
⑦Enter quit
means exiting gdb debugging mode
⑧Input set logging on
means turning on the log file function, and a gdb.txt file will be generated
⑨Input watch i
means observation point, observe the i variable
⑩Input info watchpoints
means wipe the observation point situation
-
Debugging the core file
If the core file is not generated, you need to check your ulimit limit, use "ulimit -a
", and use " " to remove the limitulimit -c unlimited
.
After lifting the restriction, compile and generate the core file and check for segfault:gdb 二进制文件 core文件
-
Debugging an executing file (such as an infinite loop)
./a.out &
means running it in the background. After execution, a process number
gdb -p pid will be returned.