所要测试的代码如下
#include <stdio.h>
int nGlobalVar = 0;
int tempFunction(int a, int b)
{
printf("tempFunction is called, a = %d, b = %d /n", a, b);
return (a + b);
}
int main()
{
int n;
n = 1;
n++;
n--;
nGlobalVar += 100;
nGlobalVar -= 12;
printf("n = %d, nGlobalVar = %d /n", n, nGlobalVar);
n = tempFunction(1, 2);
printf("n = %d", n);
return 0;
}
启动GDB
[ubuntu@VM-48-245-ubuntu ~/c_test]$ gdb
file命令载入被调试程序
(gdb-test是由gdb-test.c编译出来的可执行文件)
(gdb) file gdb-test
注意 编译时加入-g参数,输出调试信息
gcc gdb-test.c -o gdb-test -g
r命令执行(Run)被调试文件,因为尚未设置任何断点,将直接执行到程序结束
(gdb) r
Starting program: /home/ubuntu/c_test/gdb-test
n = 1, nGlobalVar = 88 /ntempFunction is called, a = 1, b = 2 /nn = 3[Inferior 1 (process 3114) exited normally]
“b”命令在 main 函数开头设置一个断点(Breakpoint)
(gdb) b main
Breakpoint 1 at 0x400559
再次使用“r”命令执行(Run)被调试程序:
(gdb) r
Starting program: /home/ubuntu/c_test/gdb-test
Breakpoint 1, main () at gdb-test.c:14
14 n = 1;
面使用“s”命令(Step)执行下一行代码
(gdb) s
15 n++;
用“p”命令(Print)看一下变量 n 的值是不是 1
(gdb) p n
$1 = 1
“q”,退出(Quit)GDB调试环境:
(gdb) q
A debugging session is active.
Inferior 1 [process 4283] will be killed.
Quit anyway? (y or n) y