本文是通过学习左耳朵皓帝的文章,详见:http://blog.csdn.net/haoel
1.使用gdb
gdb主要是用来调试c和c++程序,首先在编译前我们先把调试信息加到可执行程序当中,使用参数 -g 可以实现这一点。
dzhwen@deng:~/first$ gcc -g tst.c -o tst dzhwen@deng:~/first$ g++ -g tst.cpp -o tst
2.启动gdb
1.我们一般使用:gdb + 程序名字来启动gdb。
dzhwen@deng:~/first$ gdb tst
当然也不乏其他方法:
2、gdb
<program> core
用gdb同时调试一个运行程序和core文件,core是程序非法执行后core dump后产生的文件。
3、gdb
<program> <PID>
如果你的程序是一个服务程序,那么你可以指定这个服务程序运行时的进程ID。gdb会自动attach上去,并调试他。program应该在PATH环境变量中搜索得到。
3.常见的gdb
1.help : 查看常见的命令帮助
(gdb) help List of classes of commands: aliases -- Aliases of other commands breakpoints -- Making program stop at certain points data -- Examining data files -- Specifying and examining files internals -- Maintenance commands obscure -- Obscure features running -- Running the program stack -- Examining the stack status -- Status inquiries support -- Support facilities tracepoints -- Tracing of program execution without stopping the program user-defined -- User-defined commands Type "help" followed by a class name for a list of commands in that class. Type "help all" for the list of all commands. Type "help" followed by command name for full documentation. Type "apropos word" to search for commands related to "word". Command name abbreviations are allowed if unambiguous.
2.list,简写l:列出源码
(gdb) list 7 { 8 sum += i; 9 } 10 return sum; 11 } 12 13 int main() 14 { 15 int i; 16 long result = 0;
3.回车:重复上一次的命令
(gdb) 17 for(i = 1;i <= 100;++i) 18 { 19 result += i; 20 } 21 22 printf("result[1-100] = %ld\n",result); 23 printf("result[1-250] = %d\n",func(250)); 24 return 0; 25 } 26
4.break + 数字 或者 break + 函数名 —— 设置断点
(gdb) break 15 Breakpoint 1 at 0x804841a: file tst.c, line 15. (gdb) break func Breakpoint 2 at 0x80483ea: file tst.c, line 5.
5.info + 信息 —— 查看各种信息
(gdb) info break —— 查看断点信息 Num Type Disp Enb Address What 1 breakpoint keep y 0x0804841a in main at tst.c:15 2 breakpoint keep y 0x080483ea in func at tst.c:5
6.run(简写r)—— 运行程序,遇到断点自动中断。
(gdb) run Starting program: /home/dzhwen/first/tst Breakpoint 1, main () at tst.c:16 16 long result = 0;
7.next(简写n) —— 单条语句执行。
(gdb) next 17 for(i = 1;i <= 100;++i)
8.continue —— 继续执行(直到下一个断点中止)
(gdb) continue Continuing. result[1-100] = 5050 Breakpoint 2, func (n=250) at tst.c:5 5 int sum = 0,i;
9.print(简写p) + 变量名 —— 打印变量的值,print命令简写。
(gdb) p sum $1 = 0 (gdb) n 6 for(i = 0;i < n;++i) (gdb) p i $2 = 1
10,bt —— 查看程序堆栈(包括main函数和其他调用的函数)
(gdb) bt #0 func (n=250) at tst.c:6 #1 0x08048461 in main () at tst.c:23
11.finish —— 运行至函数退出
(gdb) finish Run till exit from #0 func (n=250) at tst.c:6 0x08048461 in main () at tst.c:23 23 printf("result[1-250] = %d\n",func(250)); Value returned is $7 = 31125
12.quit(简写q) —— 退出gdb
(gdb) quit
gdb初步就这些了吧,多多指教!