将add.c生成动态链接库,在test.c中调用add.c中的add函数
add.c代码如下:
int add(int a,int b){
return a+b;
}
gcc add.c -shared -o libadd.so 生成动态链接库libadd.so
test.c代码如下:
#include <stdio.h>
#include <dlfcn.h>
int main(){
typedef int(*t_add)(int a,int b);
void *handle;
handle = dlopen("./libadd.so",RTLD_LAZY);
t_add myadd = (t_add)dlsym(handle,"add");
printf("2+3 = %d\n",myadd(2,3));
dlclose(handle);
}
gcc test.c -o test -ldl 生成test可执行文件
./test 运行程序得到结果: 2 + 3 = 5