gdb调试

来源:互联网 发布:java python php 对比 编辑:程序博客网 时间:2024/05/21 04:16

一般来说,GDB主要帮忙你完成下面四个方面的功能:

    1、启动你的程序,可以按照你的自定义的要求随心所欲的运行程序。
    2、可让被调试的程序在你所指定的调置的断点处停住。(断点可以是条件表达式)
    3、当程序被停住时,可以检查此时你的程序中所发生的事。
    4、动态的改变你程序的执行环境。

#include <stdio.h>int main(){        int i=0;        for(i=0;i<100;i++)        {                printf("the num is: %d \n",i);        }        return 0;}

jack@ubuntu:~/sources$ gdb forc
GNU gdb (GDB) 7.2-ubuntu
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 "i686-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /home/jack/sources/forc...done.
(gdb) l <-------------------- l命令相当于list,从第一行开始例出原码。
1 #include <stdio.h>
2 int main()
3 {
4 int i=0;
5 for(i=0;i<100;i++)
6 {
7 printf("the num is: %d \n",i);
8 }
9 return 0;
10 }
(gdb) break 7 <-------------------- 设置断点在第7行
Breakpoint 1 at 0x80483df: file forc.c, line 7.
(gdb) break 8 <-------------------- 设置断点在第8行
Breakpoint 2 at 0x8048400: file forc.c, line 8.
(gdb) info break <-------------------- 断点信息
Num     Type           Disp Enb Address    What
1       breakpoint     keep y   0x080483df in main at forc.c:7
2       breakpoint     keep y   0x08048400 in main at forc.c:8
(gdb) r   <-------------------- 执行直到第一个断点 
Starting program: /home/jack/sources/forc 
Breakpoint 1, main () at forc.c:7
7 printf("the num is: %d \n",i);
(gdb) n <-------------------- 单步执行
the num is: 0 
5 for(i=0;i<100;i++)
(gdb) c <--------------------继续执行continue
Continuing.
Breakpoint 1, main () at forc.c:7
7 printf("the num is: %d \n",i);

(gdb) p i <---------------------打印变量i (print)
$1 = 1

(gdb) bt   <--------------------- 查看函数堆栈。
#0  main () at forc.c:7
 finish    <--------------------- 退出函数
(gdb) c
Continuing.
the num is: 1 
Breakpoint 1, main () at forc.c:7
7 printf("the num is: %d \n",i);
(gdb) q  <---------------------退出
A debugging session is active.
Inferior 1 [process 8888] will be killed.

使用GDB
一般来说GDB主要调试的是C/C++的程序。要调试C/C++的程序,首先在编译时,我们必须要把调试信息加到可执行文件中。使用编译器(cc/gcc/g++)的 -g 参数可以做到这一点。如:
> cc -g hello.c -o hello
> g++ -g hello.cpp -o hello

如果没有-g,你将看不见程序的函数名、变量名,所代替的全是运行时的内存地址。当你用-g把调试信息加入之后,并成功编译目标代码以后,让我们来看看如何用gdb来调试他。
启动GDB的方法有以下几种:
1、gdb <program>
program也就是你的执行文件,一般在当然目录下。
2、gdb <program> core
用gdb同时调试一个运行程序和core文件,core是程序非法执行后core dump后产生的文件。
3、gdb <program> <PID>
如果你的程序是一个服务程序,那么你可以指定这个服务程序运行时的进程ID。gdb会自动attach上去,并调试他。program应该在PATH环境变量中搜索得到。
GDB启动时,可以加上一些GDB的启动开关,详细的开关可以用gdb -help查看。我在下面只例举一些比较常用的参数:
-symbols <file>
-s <file>
从指定文件中读取符号表。
-se file
从指定文件中读取符号表信息,并把他用在可执行文件中。
-core <file>
-c <file>
调试时core dump的core文件。
-directory <directory>
-d <directory>
加入一个源文件的搜索路径。默认搜索路径是环境变量中PATH所定义的路径。

原创粉丝点击