GDB不同文件断点调试

GDB不同文件断点调试


作为一个linux下C/C++开发人员,调试工具是必不可少的一项技能,在windows平台,会有很多工具给我们用,比如VS,自带很强大的调试工具。当然,linux平台夜市毫不逊色,GDB工具是一个非常强大的代码调试工具。今天主要介绍的是GDB在多文件中的调试方法,不会一一介绍基础命令的。


一、同一个目录中的文件
现在,有三个文件,分别为main.cpp、test1.cpp、test2.cpp文件,这个是很简单的程序,只是为了说明调试过程。

代码如下:

head.h
#include <iostream>
using namespace std;

void test1();
void test2();
test2.cpp
#include "head.h"

void test2()
{
    cout<<"test2"<<endl;
}

#include "head.h"

void test1()
{
    cout<<"test1"<<endl;
}

#include "head.h"

int main()
{
    test1();
    test2();
    return 0;
}

这部分代码都在同一个目录下:GDB/ManyFiles


Step1:
编译代码,记得加参数 -g

GDB/ManyFiles$ g++ main.cpp test1.cpp test2.cpp -o test -g
GDB/ManyFiles$ ls
head.h  main.cpp  test  test1.cpp  test2.cpp

Step 2:
开始调试

GDB/ManyFiles$ gdb test 

Step 3:
同一个文件夹中的文件,我们可以用 break file1.cpp: linenum

(gdb) l 1
1	#include "head.h"
2	
3	int main()
4	{
5	    test1();
6	    test2();
7	    return 0;
8	}
(gdb) b test1.cpp:4
Breakpoint 1 at 0x4008b2: file test1.cpp, line 4.

Step 4:
启动程序,程序会在断点处停止运行

(gdb) l 1
1	#include "head.h"
2	
3	int main()
4	{
5	    test1();
6	    test2();
7	    return 0;
8	}
(gdb) b test1.cpp:4
Breakpoint 1 at 0x4008b2: file test1.cpp, line 4.
(gdb) run
Starting program: /mnt/hgfs/share/C++/GDB/ManyFiles/test 

Breakpoint 1, test1 () at test1.cpp:5
5	    cout<<"test1"<<endl;

Step 5:
退出GDB调试

(gdb) c
Continuing.
test1
test2
[Inferior 1 (process 56202) exited normally]
(gdb) quit


上面这个步骤就是我们的多文件调试,当然,在大型项目中,文件往往都是在不同的文件夹中,所以,我们也要掌握在不同问价夹中调试的办法。

二、不同文件夹中文件调试
代码还是上面的代码,只是会放在不同的目录下:
GDB/test1:test1.cpp
GDB/test2:test2.cpp
GDB/ManyFiles:main.cpp

Step1:
编译代码,记得加参数 -g

GDB/ManyFiles$ GDB/ManyFiles$ g++ main.cpp ../test1/test1.cpp ../test2/test2.cpp -o test -g
GDB$ ls
ManyFiles  test1  test2

Step 2:
开始调试

GDB/ManyFiles$ gdb test 

Step 3:
不同文件夹中的文件,我们可以用 directory 命令修改路径

(gdb) directory ../test1/
Source directories searched: /mnt/hgfs/share/C++/GDB/ManyFiles/../test1:$cdir:$cwd 
(gdb) b test1.cpp:2
Breakpoint 1 at 0x4008b2: file ../test1/test1.cpp, line 2.
(gdb) r
Starting program: /mnt/hgfs/share/C++/GDB/ManyFiles/test 

Breakpoint 1, test1 () at ../test1/test1.cpp:5
5	    cout<<"test1"<<endl;
(gdb) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x00000000004008b2 in test1() at ../test1/test1.cpp:2
	breakpoint already hit 1 time
(gdb) 


Step 4:
启动程序,程序会在断点处停止运行

(gdb) l 1
1	#include "head.h"
2	
3	int main()
4	{
5	    test1();
6	    test2();
7	    return 0;
8	}
(gdb) b test1.cpp:4
Breakpoint 1 at 0x4008b2: file test1.cpp, line 4.
(gdb) run
Starting program: /mnt/hgfs/share/C++/GDB/ManyFiles/test 

Breakpoint 1, test1 () at test1.cpp:5
5	    cout<<"test1"<<endl;

Step 5:
退出GDB调试

(gdb) c
Continuing.
test1
test2
[Inferior 1 (process 56202) exited normally]
(gdb) quit

这就是今天介绍的GDB多文件断点调试的全部内容。
想了解学习更多C++后台服务器方面的知识,请关注:
微信公众号:C++后台服务器开发

发布了197 篇原创文章 · 获赞 68 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/Travelerwz/article/details/103657440