Linux 包含了一个叫 gdb 的 GNU 调试程序. gdb 是一个用来调试 C 和 C++ 程序的强力调试器. 它使你能在程序运行时观察程序的内部结构和内存的使用情况. 以下是 gdb 所提供的一些功能:
- 它使你能监视你程序中变量的值.
- 它使你能设置断点以使程序在指定的代码行上停止执行.
- 它使你能一行行的执行你的代码.
以下演示一个example.c程序的调试过程:example.c文件内容如下,
1 #include2 #include 3 #include 4 5 void my_print1(char *string); 6 void my_print2(char *string); 7 8 main() 9 { 10 char my_string[] = "hello there"; 11 my_print1(my_string); 12 my_print2(my_string); 13 } 14 15 void my_print1(char *string) 16 { 17 printf ("The string is %s\n", string); 18 } 19 20 void my_print2(char *string) 21 { 22 char *string2; 23 int size, i; 24 25 size = strlen (string); 26 string2 = (char *) malloc (size + 1); 27 28 for (i = 0; i < size; i++) 29 string2[size - i] = string[i]; 30 31 string2[size+1] = '\0'; 32 33 printf ("The string printed backward is %s\n", string2); 34 }
1.编译时,打开-g选项编译程序,编译后的可执行程序包括调试信息(备注:-E 预处理,生成.i文件;-S 编译,生成.s文件; -c 汇编,生成.o目标文件)
lxw@RD004:~/test/dir_example$ gcc -g example.c -o example
lxw@RD004:~/test/dir_example$ gdb
GNU gdb (GDB) 7.2-ubuntuCopyright (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 "x86_64-linux-gnu".For bug reporting instructions, please see:http://www.gnu.org/software/gdb/bugs/.2.通过file命令加载可执行文件:
(gdb) file exampleReading symbols from /home/lxw/test/dir_example/example...done.3.通过run命令执行
(gdb)runStarting program: /home/lxw/test/dir_example/example
The string is hello thereThe string printed backward isProgram exited with code 040.
程序异常退出。
4.(gdb) list
1 #include<stdio.h>2 #include<stdlib.h>3 #include<string.h>45 void my_print1(char *string);6 void my_print2 (char *string);78 main()9 { 10 char my_string[] = "hello there";每次显示十行代码,再次输入list将显示后十行。
5.(gdb) break 29
Breakpoint 1 at 0x4006ad: file example.c, line 29.设置断点在29行
6.(gdb) next
Breakpoint 1, my_print2 (string=0x7fffffffe2e0 "hello there") at example.c:29
29 string2[size - i] = string[i];单步运行,类似命令step. (简化命令 n)7.(gdb) continue
Continuing.Breakpoint 1, my_print2 (string=0x7fffffffe2e0 "hello there") at example.c:29
29 string2[size - i] = string[i];继续往下执行 (简化命令 c)
8.(gdb) print i
$3 = 3打印变量i的值(简化命令 p)
9.(gdb) info break
Num Type Disp Enb Address What1 breakpoint keep y 0x00000000004006ad in my_print2 at example.c:29 breakpoint already hit 4 times查看所有断点信息
10.(gdb) help commandname
查看对应commandname的使用方法,如help breakpoints
11.(gdb) quit
退出gdb高度程序
以上为简单的GDB调试程序例子,详细见gdb帮助文档,附上一篇介绍不错的文章地址,作为收藏[]