1.共享库源码
lib.hint function(void);lib.c
#include "lib.h" #include <stdio.h> int function(void){ printf("TK--------->>>>this is sharelib function\n"); }2.编译
gcc -shared -fPIC -o libfunc.so lib.c生成libfunc.so
二、共享库的静态装载
1.测试用例
main.c
#include <stdio.h> #include "lib.h" int main(){ int a = function(); }
2.编译
gcc -o main main.c -L. -lfunc
3.添加环境变量
vi /home/tankai/.bashrc
export LD_LIBRARY_PATH+=:/home/lianxi/share/static
即时生效:
source /home/tankai/.bashrc
三、共享库的动态装载
1.测试用例
main.c
#include <stdio.h> #include <dlfcn.h> #define PATH "../static/libfunc.so" void *handle = NULL; int (*test) (void); int main(){ handle = dlopen(PATH, RTLD_NOW|RTLD_GLOBAL); if(handle == NULL){ printf("dlopen:%s\n",dlerror); } dlerror(); test = (int(*)(int))dlsym(handle,"function"); if(test == NULL){ printf("dlsym:%s\n",dlerror()); dlclose(handle); } int a = test(); dlclose(handle); }
2.编译
gcc -o main main.c -L. -ldl