gdb是一个用来调试C和C++程序的功能强大的调试器,它可以在程序运行时,观查程序内部结构和内存的使用情况。
主要功能
(1) 监视程序中的变量。
(2) 设置断点,让程序在指定的代码行暂停。
(3) 单步执行。
(4) 分析崩溃程序产生的核文件。
gdb调试小例
使用gdb调试一个非常简单的c++程序,使用gdb的几个常用的主要功能监视变量、设置断点、单步执行。
(1)源文件:helloworld.cpp
#include<iostream>
using namespace std;
int main()
{
int counter=0;
int i=0;
for(;counter<10;++counter)
{
cin>>i;
cout<<"i is: "<<i<<endl;
}
return 0;
}
(2)编译源文件
使用 “-ggdb3”选项编译,编译后“gdb”可以判断编译后的代码和源程序代码的关系。否则,gdb无法判断源程序中的哪一行代码被执行。
g++ -ggdb3 -o helloworld helloworld.cpp
(3)调试程序
gdb+程序名
adver@adver-VirtualBox:~/cproject$ gdb helloworld
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from helloworld...done.
(gdb)
设置断点:在main函数处,设置断点
(gdb) break main
Breakpoint 1 at 0x400936: file helloworld.cpp, line 6.
设置断点:在xxx.cpp的第100行设置断点
(gdb) b xxx.cpp:100
执行程序:run。程序运行到断点处(第6行)停止。
(gdb) run
Starting program: /home/adver/cproject/helloworld
Breakpoint 1, main () at helloworld.cpp:6
6 int counter=0;
单步执行:step或s
s
7 int i=0;
(gdb) s
8 for(;counter<10;++counter)
监视变量:display。使用该命令观测变量后,程序每次暂停时(断点或单步执行),会显示变量的值。
(gdb)display counter
1: counter = 0
(gdb) display i
2: i = 0
(gdb) s
Breakpoint 2, main () at helloworld.cpp:10
10 cin>>i;
2: i = 0
1: counter = 0
(gdb) s
10
11 cout<<"i is: "<<i<<endl;
2: i = 10
1: counter = 0
注意:上面最后一个“s”输入后,会执行”cin>>i”,因此输入10给变量i。
(gdb) s
i is: 10
8 for(;counter<10;++counter)
2: i = 10
1: counter = 0
(gdb) s
10 cin>>i;
2: i = 10
1: counter = 1
(gdb) s
2
11 cout<<"i is: "<<i<<endl;
2: i = 2
1: counter = 1
(gdb) s
i is: 2
8 for(;counter<10;++counter)
2: i = 2
1: counter = 1
next命令:它的功能和step类似,但它不会进入到程序里面(如:调试执行自己写的某函数时,step会进入该函数里,next则不会),本例没有这种情况,所以next和step效果看起来一样。
(gdb) n
10 cin>>i;
2: i = 2
1: counter = 2
(gdb) n
20
11 cout<<"i is: "<<i<<endl;
2: i = 20
1: counter = 2
(gdb) next
i is: 20
8 for(;counter<10;++counter)
2: i = 20
1: counter = 2
输出调用栈:在程序崩溃、异常退出时,输出函数调用栈,对查找Bug很有帮助。
# 你也可以在函数中,加入abort()函数,让程序运行到此处时,主动崩溃。
# 输出调用栈
gdb ./youProgram
# 程序崩溃后输入如下命令,显示函数调用栈
bt
退出调试
(gdb) q
A debugging session is active.
Inferior 1 [process 3451] will be killed.
Quit anyway? (y or n) y
adver@adver-VirtualBox:~/cproject$