这个math.c
#include<stdio.h>
int add(int num1, int num2)
{
return num1 + num2;
}
int sub(int num1, int num2)
{
return num1 - num2;
}
int mul(int num1, int num2)
{
return num1 * num2;
}
int div(int num1, int num2)
{
return num1 / num2;
}
执行:
gcc -shared -fpic -lm -ldl -o lib_math.so math.c
生成了: lib_math.so动态库文件
这个testmath.c
#include <stdio.h>
#include <stdlib.h>
#include "dlfcn.h"
int main(void) {
void * handle;
int (*fcn) (int x, int y);
const char * errmsg;
handle = dlopen("./lib_math.so", RTLD_NOW);
if(handle == NULL) {
fprintf(stderr, "Failed to load math.so: %s\n", dlerror());
return 1;
}
dlerror();
fcn = dlsym(handle,"add");
if((errmsg = dlerror()) != NULL) {
printf("%s\n",errmsg);
return 1;
}
printf("%d\n",fcn(1,5));
dlclose(handle);
return 0;
}
运行:
gcc -o testmath testmath.c -ldl
生成: testmath 可执行文件
执行testmath即可。
附上图:
图一:math.c源码
图二:编译math.c
图三:testmath.c源码
图四:编译testmath.c
图五:运行testmath得到结果
收工。