系统函数库使用
linux系统函数库位于/usr/lib和/lib目录下
#include <math.h>
#cc test.c -lm -o test
动态库创建
1).编译时指定-fPIC 通知gcc产生可以重定位的与位置无关的目标代码
2).链接时指定-shared 使gcc编译器生成动态链接库
动态库使用
通过设置环境变量LD_LIBRARY_PATH 或者 dlopen方式加载动态链接库
调用dlopen系列函数需要包含头文件 dlfcn.h,在链接时要链接函数库libdl.a
#include <stdio.h>
int addfunc(int x,cc y)
{return x+y;}
#cc -fPIC -c exp.c
#cc -shared exp.o -o exp.so
#include <stdio.h>
#include <dlfcn.h>
main()
{
void *handle;
int (*callfunc)(int,int);
if((handle = dlopen("./exp.so",RTLD_LAZY)) == NULL)
{
fprintf(stderr,"dlopen:%s\n",dlerror());
exit(0);
}
dlerror();
if((callfunc = dlsym(handle,"addfunc")) == NULL)
{
fprintf(stderr,"dlsym:%s\n",dlerror());
exit(0);
}
printf("1+2=%d\n",callfunc(1,2));
dlclose(handle);
}
#cc -c -o test.c
#cc test.o -ldl -o test
=========更多说明==========&