日期:2014-05-16  浏览次数:20294 次

[调试技术]_[命令行使用gdb调试程序简单应用]

使用场景:

1.服务端编程时,如果由于系统限制只能使用命令行模式编写代码,那么也就是不能使用图形ide工具了。

2.当ide对gdb支持不好时.

3.系统资源不足时.

4.只想使用editplus快速写例子程序时.

5.环境mingw g++ 4.4,gdb 7.2,编译时记得加上-g选项,链接时不要加-s选项.


文件1:C:\workspace\script-test\test_gdb\test_gdb.cpp

#include <stdio.h>

typedef struct TestGdb TestGdb;

struct TestGdb
{
	int i;
	TestGdb *gdb_; 
};

int main(int argc, char *argv[])
{
	printf("Hello, world\n");

	TestGdb gdb1;
	TestGdb gdb2;
	gdb2.i = 100;
    gdb1.i = 10;
    gdb1.gdb_ = &gdb2;

	int i = 9;
	int b = i/0;
    printf("Hello, world %d\n",b);
	return 0;
}

2.调试过程:

启动程序使用gdb [文件路径.exe]

	C:\workspace\script-test\test_gdb/test_gdb.cpp: In function 'int main(int, char*
	*)':
	C:\workspace\script-test\test_gdb/test_gdb.cpp:22: warning: division by zero
	GNU gdb (GDB) 7.2
	Copyright (C) 2010 Free Software Foundation, Inc.
	License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
	This is free software: you are free to change and redistribute it.
	There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
	and "show warranty" for details.
	This GDB was configured as "mingw32".
	For bug reporting instructions, please see:
	<http://www.gnu.org/software/gdb/bugs/>...
	Reading symbols from C:\workspace\script-test\test_gdb/test_gdb.exe...done.
	(gdb) break C:\workspace\script-test\test_gdb\test_gdb.cpp:22
	Breakpoint 1 at 0x4013fa: file C:\workspace\script-test\test_gdb/test_gdb.cpp, l
	ine 22.
	(gdb) run
	Starting program: C:\workspace\script-test\test_gdb/test_gdb.exe
	[New Thread 5688.0x6ac]
	Hello, world

	Breakpoint 1, main (argc=1, argv=0x342ae8)
		at C:\workspace\script-test\test_gdb/test_gdb.cpp:22
	22              int b = i/0;
	(gdb) print gdb1
	$1 = {i = 10, gdb_ = 0x22ff08}
	(gdb) print gdb1:gdb_
	A syntax error in expression, near `:gdb_'.
	(gdb) print gdb1.gdb_
	$2 = (TestGdb *) 0x22ff08
	(gdb) print gdb1.gdb_.i
	$3 = 100
	(gdb) record
	Process record: the current architecture doesn't support record function.
	(gdb) continue
	Continuing.

	Program received signal SIGFPE, Arithmetic exception.
	0x00401406 in main (argc=1, argv=0x342ae8)
		at C:\workspace\script-test\test_gdb/test_gdb.cpp:22
	22              int b = i/0;
	(gdb) print gdb1.gdb_.i
	$4 = 100
	(gdb) q
	A debugging session is active.

			Inferior 1 [process 5688] will be killed.

	Quit anyway? (y or n)








3.Gdb的部分参数:

注意,开始运行时输入run 回车才会开始调试。

(gdb) break filename:line-number
(gdb) break filename:function-name    
要想设置一个条件断点,可以利用break if命令,如下所示:
(gdb) break line-or-function if expr    
例:    (gdb) break 46 if testsize==100    
从断点继续运行:countinue 命令