生成动态库
文件名:TestSO.c
#include "testso.h" #include <stdio.h> #include <stdlib.h> void test_a() { printf("this is in test_a...\n"); } void test_b() { printf("this is in test_b...\n"); } void test_c() { printf("this is in test_c...\n"); }
编译成动态库命令
gcc testso.c -fPIC -shared -o libtestso.so
动态库隐式链接
当动态库的位置或者名字发生改变时,程序将无法运行。
复制libtestso.so到/usr/lib目录下。要有root权限才能复制到系统目录中。
文件名:main.c
#include "testso.h" int main() { test_a(); test_b(); test_c(); return 0; }
生成可执行程序,名为test。
gcc main.c -o test -ltestso -L/usr/lib
使用ldd测试链接是否成功,即是否链接上了动态库:
ldd test
linux-gate.so.1 => (0xb778c000)
libtestso.so => /usr/lib/libtestso.so (0xb7776000)
libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xb75cc000)
/lib/ld-linux.so.2 (0xb778d000)
运行结果如下:
this is in test_a...
this is in test_b...
this is in test_c...
动态库显示链接
文件名:dlltest.c
#include "testso.h" #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <dlfcn.h> #include <sys/types.h> int main() { void * pHandle; void (*pFunc)();
//RTLD_NOW:将共享库中的所有函数加载到内存//RTLD_LAZY:会推后共享库中的函数的加载操作,直到调用dlsym()时方加载某函数 pHandle = dlopen("./libtestso.so", RTLD_NOW); if(!pHandle) { printf("Can't find libtestso.so\n"); return -1; } else { printf("find libtestso.so\n"); } void (*pTest1)() = dlsym(pHandle, "test_a"); if(pTest1) { (*pTest1)(); } else { printf("load test_a function is error\n"); } return 0; }
生成可执行程序,名为dlltest。
gcc dlltest.c -o dlltest -ldl
编译时要使用系统的共享库dl。其中有dlopen、dlsynm等函数。
运行结果如下:
find libtestso.so
this is in test_a...