gdb调试时更换源码目录

本文将要学习如何在使用gdb调试时切换源代码目录。

示例代码

#include <iostream>

int main()
{
    std::string h_w{"Hello World"};
    std::cout << h_w << std::endl;
    return 0;
}

操作系统:Linux

编译器:g++

编译指令:g++ test.cpp -o test -O2 -g

源代码目录:/home/test

准备工作

为了实验,现将源代码和可执行程序都换一个目录,使其在调试时找不到源码。

步骤一:源代码目录改名

命令:mv /home/test /home/test1

[root@localhost test1]# ll
total 112
-rwxr-xr-x. 1 root   root   110264 Jan 27 09:14 test
-rw-rw-r--. 1 root   root   121 Jan 27 09:04 test.cpp

步骤二:移走可执行程序

命令:mv test /usr/local/bin

[root@localhost test1]# ll /usr/local/bin/test
-rwxr-xr-x. 1 root root 110264 Jan 27 09:14 /usr/local/bin/test

步骤三:调试可执行程序

命令:(1) cd /usr/local/bin

          (2) gdb test

          (3) info sources

[root@localhost bin]# gdb test
GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-119.el7
Copyright (C) 2013 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-redhat-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /usr/local/bin/test...done.
(gdb) l
1    test.cpp: No such file or directory.
(gdb) info sources
Source files for which symbols have been read in:

/home/test/test.cpp, /opt/rh/devtoolset-9/root/usr/include/c++/9/bits/ostream_insert.h, /usr/include/wctype.h, /usr/include/errno.h,
......

从以上输出可知,已经看不到源代码了,gdb搜索源码/home/test/test.cpp,但在步骤一中已经将目录/home/test改名为了/home/test1,所以gdb找不到这个源码文件。

设置正确的源码目录

为了能在gdb中正常地显示程序源代码,需要在gdb中进行如下设置。

步骤一:切换源码目录到正确的目录

命令:(1) set substitute-path /home/test /home/test1

           (2) l

(gdb) set substitute-path /home/test /home/test1
(gdb) l
1    #include <iostream>
2    
3    int main()
4    {
5        std::string h_w{"Hello World"};
6        std::cout << h_w << std::endl;
7        return 0;
8    }
(gdb)

从以上输出可知,切换源代码目录成功了,能够在gdb中正常显示源代码了。

步骤二:查看gdb中的源代码信息

命令:info sources

(gdb) info sources
Source files for which symbols have been read in:

/home/test1/test.cpp, /opt/rh/devtoolset-9/root/usr/include/c++/9/bits/ostream_insert.h, /usr/include/wctype.h, /usr/include/errno.h,
......

此时,我们可以看到gdb中的源代码目录已经切换到了/home/test1。

结束语

此项技巧也适用于在没有源代码的机器上调试程序时,将源代码拷贝上去,并在gdb中设置显示源码。

  • 27
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

PerfMan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值