调试器GDB的使用

1.GDB使用实例

#include <stdio.h>

int add(int n,int m)
{
	int a;
	a = n + m;
	return a;
}

int sub(int n,int m)
{
	int b;
	b = n - m;
	return b;
}
int main(int argc,char *argv[])
{
	int sum,diff;
	sum  = add(3,2);
	printf("n + m = %d\n",sum);
	diff = sub(3,2);
	printf("n - m = %d\n",diff);
	return 0;
}

         将此程序用GCC编译时要加上 “-g” 选项,“ -g " 选项告诉gcc编译器生成包含调试信息的可执行文件。

1.1 进入GDB

        gdb 可执行文件

linux@ubuntu:~$ gdb a.out 
GNU gdb (Ubuntu 8.1.1-0ubuntu1) 8.1.1
Copyright (C) 2018 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.out...done.
(gdb) 

1.2 查看文件

        list 或者 l

(gdb) list
5		int a;
6		a = n + m;
7		return a;
8	}
9	
10	int sub(int n,int m)
11	{
12		int b;
13		b = n - m;
14		return b;
(gdb) 

1.3 设置断点

设置断点可以使程序执行到某个位置停止,在该位置处可以方便的查看变量的值,堆、栈等情况 

注意在设置断点是指代码运行到对应行之前暂停。

可以设置多个断点

b 行号

(gdb) b 5
Breakpoint 1 at 0x654: file 2.c, line 5.

1.4 查看断点处的情况

        info b

(gdb) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x0000000000000654 in add at 2.c:5
2       breakpoint     keep y   0x0000000000000654 in add at 2.c:6

1.5 运行代码

        run

        程序运行到断点处就停止了。

(gdb) run
Starting program: /home/linux/a.out 

Breakpoint 1, add (n=3, m=2) at 2.c:6
6		a = n + m;

1.6 查看变量名

        在程序停止运行后,就可以查看断点处的相关变量值。

        p 变量名

(gdb) p n
$1 = 3
(gdb) p m
$2 = 2

1.7 单步运行

        n

(gdb) n
7		return a;
(gdb) n
8	}
(gdb) n
main (argc=1, argv=0x7fffffffdf68) at 2.c:20
20		printf("n + m = %d\n",sum);

1.8 程序继续运行

        c

(gdb) c
Continuing.
n + m = 5
n - m = 1
[Inferior 1 (process 5424) exited normally]

1.9 删除断点

         delete 编号

(gdb) delete 1

2.0 退出GDB 

        q

(gdb) q

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值