手把手GDB调试

文章介绍了如何使用GCC编译器以-o0和-g参数生成调试信息,以便在CMake中以Debug模式构建项目。通过GDB调试器设置断点,查看变量值,有效地调试代码。当调试运行中的程序时,可以使用gdbattach命令连接到进程进行调试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

确保你的程序有可调式的信息

使用gcc编译一个程序 ,带上一些额外的参数

-o0 -g

-o0 :避免编译器优化,使用最低的优化等级,默认的编译选项
-g :生产调试信息

如果你已经有一个工程demo,使用cmake时注意使用Debug模式,如:
SET(CMAKE_BUILD_TYPE "Debug")

调试一个简单的程序

示例代码
在这里插入图片描述
在130行出打断点,并读取变量值
gdb的调试记录如下:

root@1124ceb4e92e:/data/smc/Cool/build# gdb cool
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 cool...done.
(gdb) b 130
Breakpoint 1 at 0x40e8a0: file /data/smc/Cool/src/main.cpp, line 130.
(gdb) r
Starting program: /data/smc/Cool/build/cool
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
[New Thread 0x7ffff1bbc700 (LWP 3502)]
[New Thread 0x7fffef3bb700 (LWP 3503)]
[New Thread 0x7fffeebba700 (LWP 3504)]
[New Thread 0x7fffea3b9700 (LWP 3505)]
[New Thread 0x7fffe7bb8700 (LWP 3506)]
[New Thread 0x7fffe73b7700 (LWP 3507)]
[New Thread 0x7fffe4bb6700 (LWP 3508)]

Thread 1 "cool" hit Breakpoint 1, main (argc=1, argv=0x7ffffffa9518) at /data/smc/Cool/src/main.cpp:130
130             ++value_a;
(gdb) print value_a
$1 = 0
(gdb) c
Continuing.

Thread 1 "cool" hit Breakpoint 1, main (argc=1, argv=0x7ffffffa9518) at /data/smc/Cool/src/main.cpp:130
130             ++value_a;
(gdb) print value_a
$2 = 1
(gdb)

调试一个正在运行的程序

gdb attatch `pidof cool`

启动调试并设置断点
在这里插入图片描述
设置断点是出现了No line 130 in the current file,调试信息缺失了;
利用symbol-file加载运行程序的debug信息
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值