本文将要学习如何在使用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中设置显示源码。