- 准备一些简单的代码
这些文件都处于同一目录下
test.h声明了一个函数
#include<iostream>
#include<string>
void My_Print(std::string str);
test.cpp负责实现头文件的函数
#include"test.h"
void My_Print(std::string str)
{
std::cout<<str<<std::endl;
}
tt.cpp用于测试的文件
#include"test.h"
int main()
{
My_Print("hello world");
return 0;
}
- 编译运行这个文件
g++ ./tt.cpp -o tt
出现报错
/usr/bin/ld: /tmp/ccUJfOAd.o: in function `main':
tt.cpp:(.text+0x4a): undefined reference to `My_Print(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
collect2: error: ld returned 1 exit status
因为没找到函数的实现。
添加上函数实现的文件test.cpp
g++ ./tt.cpp -o tt test.cpp
成功编译并运行。
-
将其打包成.so动态库
使用命令g++ -fPIC -shared test.cpp -o libmy_test.so
就在当前目录生成了一个libmy_test.so*
动态库
使用.so生成tt
文件
g++ tt.cpp -o tt ./libmy_test.so
现在已经成功了一半,如果要分享给别人自己实现的库,就可以将.h
文件和.so
文件传给他就行了。 -
在环境中配置动态库
在linux上,通常在/usr/lib
和/usr/local/lib
下寻找.a
与.so
文件
在/usr/include
/usr/local/include
下找*.h
文件
-
我们执行
sudo mv ~/projects/test/libmy_test.so /usr/local/lib/
sudo mv ~/projects/test/test.h /usr/local/include/
将头文件和cpp文件移动到这些地方。 -
这时候我们使用动态库重新编译测试文件
g++ ./tt.cpp -o tt -lmy_test
-
编译成功,但是运行出现报错:
./tt: error while loading shared libraries: libmy_test.so: cannot open shared object file: No such file or directory
这个表示在运行的时候找不到这个libmy_test.so文件,编译的时候寻找文件是在 /usr/lib寻找 ,但是运行的时候是在 /etc下的文件中寻找。 -
/etc/ld.so.cache
运行的时候.so库都会在这个缓存文件中寻找. -
我们打开
vim ./ld.so.conf
发现
这段路径表示包括/etc/ld.so.conf.d
所有的.conf
文件。
这个ld.so.conf.d
就是配置.so的关键。 -
cd ld.so.conf.d
vim mylib.conf
创建自己的conf文件
写入/usr/local/lib
也就是之前.so保存的路径。
sudo ldconfig
将配置写入缓存。
就会发现之前编译出的tt可以正常运行了。