Happy Niu Year.
step1: 编译一个linux动态库
头文件get.h:
#ifndef get_H
#define get_H
int get();
int set(int a);
#endif
实现文件get.cpp:
#include <stdio.h>
#include "get.h"
static int x=0;
int get(){
return x;
}
int set(int a){
x=a;
return x;
}
g++编译出一个名字为libggg.so的库:
g++ get.cpp -shared -g -fPIC -DDEBUG -o libggg.so (64bit machine)
step2: 写一个调用该库的程序
pkk.cpp
#include <stdio.h>
#include "get.h"
int main(){
int a=3;
int b=get();
int c=set(a);
int d=get();
printf("a=%d, b=%d,c=%d,d=%d\n", a,b,c,d);
}
g++编译一下子:
g++ pkk.cpp -o app -Wall -g -lggg -Lxx/xx/xx
Note: -lggg表示需要用到名字为ligbbb.so的库; -Lxx/xx/xx表示除了默认的库搜索路径之外,链接器需要到xx/xx/xx路径去搜索库文件;
运行:
假设当前所在目录为app所在目录,则:
首先,需要将libggg.so所在目录添加到环境变量中:export LD_LIBRARY_PATH=/home/xxx/Documents/learn/myLibs:LD_LIBRARY_PATH
然后运行./app 即可。
step3: gdb调试该程序
首先,gdb ./app来基于gdb启动程序.
然后, 如果你想在get.cpp文件的第7行设置断点,则,需要先将该文件的路径通过dir指令告诉gdb,所以吧,源文件是可以随便挪动的,如下文指示。
在get.cpp文件的第7行设置断点的方法: b get.cpp:7, 回车后会提示:
No source file named get.cpp.
Make breakpoint pending on future shared library load? (y or [n])
请选择y。
Note:
1)gdb设置动态库的源文件查找路径:
进入gdb之后,show dir命令,显示当前所有的查找路径。 在当前的基础上增加一个路径:dir xx/xx。 该指令在退出gdb后即失效。 曾经尝试dir xx/xx,然后get.cpp文件位于xx/xx/source/get.cpp,然后设置断点时使用b source/get.cpp:7,不行!
关于gdb查找路径:https://www.cnblogs.com/rickyk/p/4184860.html
2)gdb调试时使用配置文件: 亲测可以哦
下一个配置文件gdbConfig:
file /xx/xx/xx/app
dir /xx/xx/sourcefileDir
file表示要运行的可执行文件
dir表示你添加的源文件搜索路径,相当于你执行了一次dir /xx/xx/sourcefileDir.
ref:
https://blog.csdn.net/rikeyone/article/details/90051341
https://blog.csdn.net/xcw_1987/article/details/81942272