动态库编程
Linux中so文件为共享库;windows下dll文件为共享库;
在linux中动态库的调用函数是 dlopen(); 在Windows中动态库的调用是LoadLibrary();
Linux:
库文件 fun.c
#include <stdio.h>
#include <dlfcn.h>
int add(int a, int b) //加法
{
return a+b;
}
int sub(int a, int b) //减法
{
return a-b;
}
int mul(int a, int b) //乘法
{
return a*b;
}
int div(int a, int b) //除法
{
return a/b;
}
gcc -c so.c /
gcc fun.c -fPIC -shared -o libtest.so //文件生成动态链接库文件libtest.so
test.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <unistd.h>
#include <string.h>
typedef int(* fun_prt)(int ,int);
int main()
{
char file_url[80];
char file_name[30];
void *lib_prt;
fun_prt fun_prt= NULL;
int a=3;
int b=4;
getcwd(file_url, sizeof(file_url));
strcpy(file_name ,"/libtest.so");
strcat(file_url , file_name); //拼字符串
//printf("current working directory: %s\n", file_url);
lib_prt=dlopen(file_url, RTLD_LAZY);
if(! lib_prt)
{
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
//清除之前存在的错误
dlerror();
fun_prt=dlsym(lib_prt , "add");
if(!fun_prt)
{
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
printf("add: %d\n", (*fun_prt)(a,b));
return 0;
}
gcc -o test test.c -ldl //生成测试程序
总结 看了很多教程,在so文件不放在默认的bin文件夹,或不注册环境变量的情况下。
总是编译失败,或者运行失败。
后来修改为动态定位相同目录下指定文件夹的方式,拼接文件名,然后直接传指针才获得正确结果!