GDB调试工具

本文通过一个示例来讲述常见的gdb调试命令,下面是一段多线程程序,文件名为test_gdb.cpp。

 1 #include <iostream>
 2 #include <pthread.h>
 3 
 4 void* print_message_function(void* msg) {
 5     char* temp = 0;
 6     temp = (char*)msg;
 7     std::cout << temp << std::endl;
 8 }    
 9 
10 int main(int argc, char* argv[]) {
11     pthread_t th1, th2;
12 
13     char* msg1 = "Thread 1";
14     char* msg2 = "Thread 2";
15     int iret1 = 0;
16     int iret2 = 0;
17     iret1 = pthread_create(&th1, NULL, &print_message_function, (void*)msg1);
18     iret2 = pthread_create(&th2, NULL, &pthread_message_function, (void*)msg2);
19 
20     ptherad_join(th1, NULL);
21     pthread_join(th2, NULL);
22 
23     return 0;
24 }
GDB Demo

 在Linux平台下,用如下命令来编译这段程序,因为要用gdb来调试改程序,

所以要在该程序中加入相关的调试信息,因此在编译的时候要加上“-g”参数。

g++ -g -lpthread test_gdb.cpp -o test

如果编译通过,将会声称可执行文件test。要用gdb来调试test,在命令行

中输入:

>gdb test

会输出一段关于gdb版本和版权等信息。如果要打印出源文件,用list命令或者l(list的简写)即可。

>list(或者l)

默认打印出10行源程序,按回车键,则会继续打印出10行。

打印出源文件,可能要在源文件中加入断点,则可以执行如下命令:

>break 17(或者b 17)   

这里的17代表是源文件(gdb_test.cpp)的第17行,上述命令将会在源文件中的第17行加上断点。

同理,如果要在文件的其他地方加断点,更换行号即可。如果要查看文件中所有的断点信息,

则用如下命令:

>info breakpoints

(gdb) info breakpoints
Num     Type          Disp       Enb            Address                                               What

1       breakpoint    keep         y        0x000000000040095f              in main(int, char**)at prac_1.cpp:12
breakpoint already hit 1 time
2       breakpoint    keep         y        0x0000000000400976             in main(int, char**)at prac_1.cpp:16
3       breakpoint    keep         y        0x000000000040097d             in main(int, char**)at prac_1.cpp:18

>run(或者r)

该命令是运行可执行程序,但是程序中设置断点的话,将会在断点处暂停。

如果想要打印变量的值,可以用如下命令:

>print  msg1(或者p msg1)

 

 

 

 

 

 

 

 

 

 

posted on 2013-09-08 03:46  Persistence  阅读(232)  评论(0编辑  收藏  举报

导航