ITeye博客

gdb debug c

clouisandy · 2011-09-11 10:23 · C/C++ · 编程语言 · Markdown

用gdb可以debug c程序,简单操作如下: **step-0:**准本工作 拿下面的程序为例子


#include <stdio.h>
#include <ctype.h>

main()
{
	int c;

	while((c=getchar())!=EOF){
		if(isspace(c) && c!='\n'){
			printf("is a space!\n");
		}else if(isdigit(c)){
			printf("is a number!\n");
		}else if(isalpha(c)){
			printf("is a letter!\n");
		}
	}
	
}

**step-1:**编译

gcc -g test.c -o test

注:-g是调试参数,-o指定目标名称,这样会生成test.exe

**step-2:**进入gdb

gdb test

注:gdb

此时命令行显示:

GNU gdb 5.2.1
Copyright 2002 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 "i686-pc-mingw32"...
(gdb)

**step-3:**打断点

(gdb) list
1       #include <stdio.h>
2       #include <ctype.h>
3
4       main()
5       {
6               int c;
7
8               while((c=getchar())!=EOF){
9                       if(isspace(c) && c!='\n'){
10                              printf("is a space!\n");

注:运行list可以查看源码,一次10行 找到要打断点的行,比如第8行,可以输入

(gdb) break 8

此时显示

Breakpoint 1 at 0x4012ba: file test.c, line 8.

**step-4:**debug 现在可以运行程序了,命令是:

(gdb) run

会弹出一个新的cmd,是运行的界面,此时gdb的界面会显示:

Starting program: E:\forc\6/test.exe

Breakpoint 1, main () at test.c:8
8               while((c=getchar())!=EOF){

可以看到断点信息,此时可以单步一下:

(gdb) next

下面在运行的界面输入一个字符,比如说'a',回车 单步操作,可以在gdb界面看到如下信息:

8               while((c=getchar())!=EOF){
(gdb) next
9                       if(isspace(c) && c!='\n'){
(gdb) next
11                      }else if(isdigit(c)){
(gdb) next
13                      }else if(isalpha(c)){
(gdb) next
14                              printf("is a letter!\n");
(gdb) next

可以看到每一步的操作,但是没有打印出变量c的值,可以通过下面的命令来查看

(gdb) watch c
Hardware watchpoint 2: c

这样每次循环都可以看到c的值,如下:

Old value = 2
New value = 97

更多详细用法可以参考: http://www.huihoo.org/gnu/linux/gdb.html

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。