使用场景el-
gcc hello.c -o hello -g
GDB(GNU Debugger)是GCC的调试工具。其功能强大,主要帮忙完成下面四个方面的功能:
1)启动你的程序,可以按照你的自定义的要求随心所欲的运行程序。
2)可让被调试的程序在你所指定的调置的断点处停住(断点可以是条件表达式)。
3)当程序被停住时,可以检查此时你的程序中所发生的事。
4)动态地改变你程序的执行环境。
一般来说GDB主要调试的是C/C++的程序。
要调试C/C++的程序,首先在编译时必须要把调试信息加到可执行文件中。
//fun.c
#include
#include "head.h"
int sum(int a, int b)
{
printf("welcome call %s, %d + %d = %d\n",__FUNCTION__, a, b, a + b);
return a + b;
}
int mul(int a, int b)
{
printf("welcome call %s, %d * %d = %d\n", __FUNCTION__, a, b, a * b);
return a * b;
}
//head.h
#include
int sum(int a, int b);
int mul(int a, int b);
#include
#include
#include
#include "head.h"
typedef struct MyfunInfo
{
int fun_type; // 函数类型
int a; // 函数的第一个参数
int b; // 第二个参数
char funname[10]; // 函数名称
}MyfunInfo;
int main(int argc, char *argv[])
{
int a = 2;
int i = 0;
int a1 = 10, b1 = 5;
MyfunInfo funinfo[2];
char *Msg = "I will die !";
//Msg[0] = '1';
if (argc == 3)
{
a1 = atoi(argv[1]);
b1 = atoi(argv[2]);
funinfo[0].a = a1;
funinfo[0].b = b1;
funinfo[1].a = a1;
funinfo[1].b = b1;
}
for (int i = 0; i < 2; i++)
{
printf("i===%d, LINE=%d\n", i, __LINE__);
if (i == 0)
{
funinfo[i].fun_type = 1;
printf("begin call sum\n");
strcpy(funinfo[i].funname, "sum");
sum(funinfo[i].a, funinfo[i].b);
}
if (i == 1)
{
funinfo[i].fun_type = 2; //call mul
printf("begin call mul\n");
strcpy(funinfo[i].funname, "mul");
mul(funinfo[i].a, funinfo[i].b);
}
}
printf("say bye\n");
return 0;
}
使用编译器(cc/gcc/g++)的 -g 参数可以做到这一点。
如果没有 -g,将看不见程序的函数名、变量名,所代替的全是运行时的内存地址。
当用 -g 把调试信息加入之后,并成功编译目标代码以后,就可以用gdb来调试了。
gdb program,program 也就是你的执行文件,一般在当前目录下。
1)程序运行参数
2)工作目录
可以设置一些自动显示的变量,当程序停住时,或是在单步跟踪时,这些变量会自动显示。相关的GDB命令是display。