手把手教你gdb调试

15 篇文章 0 订阅
3 篇文章 0 订阅

微信公众号:linux码头

 

gdb使用

 

启动gdb调试的必须步骤

1、编译生成可执行文件

gcc -g xx.c -o xx

2、启动GDB

gdb xx

3、在main函数处设置断点

break main

4、运行程序

run

 

选用gdb命令对程序进行后续调试

[括号里为快捷键]

 

   list(l)             查看程序

    break(b) 函数名    在某函数入口处添加断点

    break(b) 行号         在指定行添加断点

    break(b) 文件名:行号 在指定文件的指定行添加断点

    info break          查看所有设置的断点

    delete 断点编号     删除断点

    next(n)             单步运行程序(不进入子函数)

    step(s)             单步运行程序(进入子函数)

    continue(c)         继续运行程序

    print(p) 变量名    查看指定变量值

    set var=value       设置变量的值

    quit(q)             退出

 

 

例子

 

例 利用GDB追踪变量值

#include <stdio.h>
int main()
{
    int a=0;
    int i=0;
    for(i=0;i<5;i++)
        a++;
    if(a<5)
        a*=5;
    else
        a+=10;
    return 0;
}

 

 

chh001@lucky:~$ gcc -g a.c -o a

chh001@lucky:~$ gdb a

GNU gdb (Ubuntu 7.11.1-0ubuntu1~16.5) 7.11.1

Copyright (C) 2016 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".

Type "show configuration" for configuration details.

For bug reporting instructions, please see:

<http://www.gnu.org/software/gdb/bugs/>.

Find the GDB manual and other documentation resources online at:

<http://www.gnu.org/software/gdb/documentation/>.

For help, type "help".

Type "apropos word" to search for commands related to "word"...

Reading symbols from a...done.

(gdb) b main

Breakpoint 1 at 0x4004da: file a.c, line 5.

(gdb) run

Starting program: /home/chh001/a 

Breakpoint 1, main () at a.c:5

5        int a=0;

(gdb) p a   ---->打印a

$1 = 0      ---->a为0

(gdb) s

6        int i=0;

(gdb) s

7        for(i=0;i<5;i++)

(gdb) s

8            a++;

(gdb) p a
 
$2 = 0    --->a为0

(gdb) s

7        for(i=0;i<5;i++)

(gdb) p a

$3 = 1

(gdb) s

8            a++;

(gdb) s

7        for(i=0;i<5;i++)

(gdb) s

8            a++;

(gdb) p a

$4 = 2      --->a为2

(gdb) s

7        for(i=0;i<5;i++)

(gdb) s

8            a++;

(gdb) s

7        for(i=0;i<5;i++)

(gdb) s

8            a++;

(gdb) s

7        for(i=0;i<5;i++)

(gdb) s

9        if(a<5) 

(gdb) s

12            a*=5;

(gdb) p a

$5 = 5

(gdb) s

13        return 0;

(gdb) p a

$6 = 25      ---->最终结果a为25

(gdb) q     ----->退出

A debugging session is active.

    Inferior 1 [process 47418] will be killed.

Quit anyway? (y or n) y
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值