实验源文件
头文件 test_so.h
#include "stdio.h"
void test_a();
void test_b();
void test_c();
test_a.cpp test_b.cpp test_c.cpp 都如下所示
#include "test_so.h"
void test_a()
{
printf("this is in test_a...\n");
}
主文件 test.cpp
#include "test_so.h"
int main()
{
test_a();
test_b();
test_c();
return 0;
}
编译 so
使用 g++ test_a.cpp test_b.cpp test_c.cpp -fPIC -shared -o libtitus.so
编译动态链接库 libtitus.so。
-
-fPIC 选项表示编译为位置独立的代码,不用此选项的话编译后的代码是位置相关的所以动态载入时是通过代码拷贝的方式来满足不同进程的需要,而不能达到真正代码段共享的目的
-
-shared 选项表示生成 .so 形式的动态链接库
使用 so
使用 g++ test.cpp -L. -ltitus -o test
将 test.cpp 和libtitus.so 编译链接生成可执行的 test 文件。
- -L. 为执行链接指定一个库的路径(当前路径)
- -ltitus 为执行链接指定具体的库 libtitus.so,只需要写为 titus
这时生成了 test 文件,使用 ldd test
查看调用关系
linux-vdso.so.1 => (0x00007fff77655000)
libtitus.so => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6
(0x00007f64e54fe000)
/lib64/ld-linux-x86-64.so.2 (0x00007f64e58eb000)
发现找不到 libtitus.so。执行 ./test
./test: error while loading shared libraries: libtitus.so:
cannot open shared object file: No such file or directory
还需要执行
export LD_LIBRARY_PATH=/home/hy/Practice/C++/SearchCenter:
将此动态库的目录加入到环境变量中。LD_LIBRARY_PATH 这个环境变量指示动态连接器可以装载动态库的路径,也就是程序运行时去找 so 文件的路径。