一.简单程序调试
1. 假设有一个main.cpp程序需要进行调试。
#include <iostream>
#include <vector>
#include <numeric>
#include <cmath>
using namespace std;
int fun(int a,int b )
{
return a*b;
}
int main()
{
int a=2,b=3;
vector<int> nums(4,1);
nums[1]=a;nums[3]=b;
int sum = accumulate(nums.begin(), nums.end(),1,fun);
cout<<sum<<endl;
}
makefile文件如下:
main.o:main.cpp
g++ -g main.cpp -o main
2. 调试
make之后生成了main文件,执行 gdb main ,出现如下信息,说明已经进入gdb了。
[yehanghang@SHVM001984 ~/test/cppTest]$ gdb main
GNU gdb (GDB) Red Hat Enterprise Linux (7.2-50.el6)
Copyright (C) 2010 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-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /data/dev/yehanghang/test/cppTest/main...done.
(gdb)
2.1 执行 run ,程序正常运行结束。
Starting program: /data/dev/yehanghang/test/cppTest/main
6
Program exited normally.
(gdb)
2.2 gdb常用命令
参考:https://blog.youkuaiyun.com/finish_dream/article/details/51804780
list n 显示第n行最近的10行代码。
list functionname显示以functionname的函数为中心的10行代码。
break n 在第n行设置断点。
info breakpoints 查看断点信息。
delete breakpoints 断点号 删除断点
clear n 清除第n行的断点
disable/enable n 使得编号为n的断点暂时失效或有效
display 和 watch 查看参数的值
step 使得程序逐条执行,如果跳转到其他地方,会跳过去
next 运行到下一行,直接跳过其他步骤。
2.3 基础调试
gdb main
b 12
b 15
start
step
next
display nums
q