本文讲述了Linux下编写动态库以及测试过程,读者可以根据这个过程编写自己的动态库.
本次使用两个.c文件编译成库.
//.h文件 libtest_so.h #ifndef _LIBTEST_SO_H_ #define _LIBTEST_SO_H_ h #include <stdio.h> void testA(); void testB(); #endif
//.c文件 testA.c
#include 'libtest_so.h'
void testA()
{
printf('this is test A\n');
}
//.c文件 testB.c #include 'libtest_so.h' void testB() { printf('this is test B\n'); }
gcc -shared -fPIC -o libtest.so testA.c testB.c
到此为止,我们的动态库libtest.so就编译成功了,需要注意的是编译成的库的名字必须以lib开头
//测试程序 test.c #include 'libtest_so.h' void main(){ testA(); testB(); }
gcc test.c -L. -ltest -o test
(-L.)表示需要的库在当前目录
(-ltest)链接我们的动态库
编译完测试程序再./test运行时会发生如下错误,原因是因为我们编译的动态库还未加载.
./test: error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory
此时我们可以运行ldd ./test
来查看,经查看显示:
~# ldd ./test
linux-vdso.so.1 (0x00007ffc4d8c3000)
libtest.so => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f1ebf2ef000)
/lib64/ld-linux-x86-64.so.2 (0x00007f1ebf4fb000)
打开终端输入vim /etc/ld.so.conf
,进入文件后,在文件末尾添加你编译的动态库所在的路径,作者的库在/my/lib
所以添加/my/lib
就好.路径添加完成后,再在终端输入/sbin/ldconfig -v
进行刷新.刷新后我们重新运行ldd ./test
会发现原来的libtest.so => not found
已经没有,此时的测试程序也能正常运行了.
~# ldd ./test
linux-vdso.so.1 (0x00007ffed2bff000)
libtest.so => /my/lib/libtest.so (0x00007fb9d47ef000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fb9d45fd000)
/lib64/ld-linux-x86-64.so.2 (0x00007fb9d480e000)
~#./test
this is test A
this is test B
最后加载动态库的方法不止一种,还有一种是添加环境变量,不过有的版本会出现命令不识别的情况,所以在此就推荐这一种.
静态库除了编译成库命令和动态库不一样,其他的皆可参考上面动态库的方法;
采用上面的文件编译成静态库libtest.a
//先将需要的.c文件编译成.o
gcc -c testA.c testB.c
//将上述编译的.o文件编译成静态库
ar -cr libtest.a *.o
联系客服