都说gdb是一个调试程序的好工具,我以前学习C语言的时候都是在tc下调试的,不能体会gdb的妙处。现在我终于可以试试了。
源代码egforgdb.c,如下:
#include<stdio.h>
main()
{
int i,j;
for(i=0,j=0;i<5;)
{
printf("i=%d\n",++i);
printf("j=%d\n",j++);
}
}
|
编译如下,必须加-g以便告诉gcc产生能被GNU调试器使用的调试信息以便调试程序。
gcc -o edforgdb egforgdb.c -g |
编译好程序后就可使用gdb工具调试了。运行gdb,打入gdb,回车,显示信息如下
GNU gdb Red Hat Linux (6.5-8.fc6rh)
Copyright (C) 2006 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-redhat-linux-gnu".
(gdb) Quit
(gdb)
|
键入file 可执行文件名egforgdb,即可载入文件。
(gdb) file egforgdb Reading symbols from /home/tommy/cprog/chap2/egforgdb...done. Using host libthread_db library "/lib/libthread_db.so.1".
|
在第7行设置断点,break 7,回车
(gdb) break 7
Breakpoint 1 at 0x8048375: file egforgdb.c, line 7.
|
运行程序,run,回车
(gdb) run
Starting program: /home/tommy/cprog/chap2/egforgdb
Breakpoint 1, main () at egforgdb.c:7
7 printf("i=%d\n",++i);
|
显示i的值,print i
单步运行,step,回车
(gdb) step i=1 8 printf("j=%d\n",j++); (gdb) step j=0 5 for(i=0,j=0;i<5;)
|
监视变量j的值,watch j
(gdb) watch j
Hardware watchpoint 2: j
(gdb) step
Breakpoint 1, main () at egforgdb.c:7
7 printf("i=%d\n",++i);
(gdb) step
i=2
8 printf("j=%d\n",j++);
(gdb) step
Hardware watchpoint 2: j
Old value = 1
New value = 2
0x08048393 in main () at egforgdb.c:8
8 printf("j=%d\n",j++);
(gdb) step
j=1
5 for(i=0,j=0;i<5;)
(gdb) step
Breakpoint 1, main () at egforgdb.c:7
7 printf("i=%d\n",++i);
(gdb) step
i=3
8 printf("j=%d\n",j++);
(gdb) step
Hardware watchpoint 2: j
Old value = 2
New value = 3
0x08048393 in main () at egforgdb.c:8
8 printf("j=%d\n",j++);
|
显示源文件,list
(gdb) list
3 {
4 int i,j;
5 for(i=0,j=0;i<5;)
6 {
7 printf("i=%d\n",++i);
8 printf("j=%d\n",j++);
9 }
10 }
|
终止原来的程序,kill
(gdb) kill
Kill the program being debugged? (y or n) y
|
退出gdb,quit,可回到shell提示符下
(gdb) quit
[tommy@localhost chap2]$
|
阅读(806) | 评论(0) | 转发(0) |