《C编译原理》共享库的动态加载和静态加载

来源:互联网 发布:python抓取手机号 编辑:程序博客网 时间:2024/05/18 22:46
一、共享库的编译

1.共享库源码

lib.h
int 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