测试用源码:
#include < stdio.h >
#include < unistd.h >
static void PrintMessage(int i);
static void GoToSleep(void);
int main(void)
{
int i = 100000;
while ( 1 )
{
PrintMessage( i );
GoToSleep();
i -= 1;
}
return 0;
}
void PrintMessage(int i)
{
char buf[1024];
sprintf(buf,"%d bottles of beer on the wall.\n", i);
printf("%s",buf);
}
static void GoToSleep(void)
{
sleep(3);
}
gcc -g -o gdbtest gdbtest.c
调试:
调用ps -e|grep gdbtest获取进程pid;
gdb
(gdb)attach 目的进程pid
3.使用bt来显示当前程序的函数调用栈结构(也就是函数的调用顺序)。
(gdb) bt
#0 0x00000033fd8accd0 in __nanosleep_nocancel () from /lib64/libc.so.6
#1 0x00000033fd8acb60 in sleep () from /lib64/libc.so.6
#2 0x00000000004005d7 in GoToSleep () at gdbtest.c:36
#3 0x0000000000400572 in main () at gdbtest.c:15
(gdb)
使用frame来选择程序的调试起点,也可以使用break来选择指定的行或者函数来作为断点。
(gdb) frame 3
#3 0x0000000000400572 in main () at gdbtest.c:15
15 GoToSleep();
可以通过s进入函数,通过p <变量名>输出变量值, 使用n(next)来一步一步的跟踪。
可以通过类似
p *buf@strlen(buf)之类的语法来指定输出长度。
也可以用下面这样的方法来指定将断点打在哪个文件的哪一行
b main.cpp:20