最近用到了dlopen函數,感覺挺有意思的,所以記錄一下;
首先我們先編譯一個動態庫:
1、寫一個add.c
#include<stdio.h>
#include "add.h"
int add(int a, intb)
{
return a+b;
}
其中add.h就是下面一句:
int add(int a, int b);
2、編譯add.c:
[root@loadlibrary]# gcc -fPIC -c add.c
[root@loadlibrary]# gcc -shared -o test_add.so add.c
生成文件目錄如下:
add.c
add.o
test_add.so
其中,test_add.so就是我們需要用來測試的動態庫了;
接下來測試loadlibrary:
1、測試代碼test.c:
#include<stdio.h>
#include<dlfcn.h>
int main()
{
void* dp=NULL;
int (*add_function)(int, int);
dp = dlopen("test_add.so",RTLD_LAZY );
if(dp==NULL)
{
printf("dlopen failed\n");
return 0;
}
add_function = dlsym(dp, "add");
int result = add_function(3, 4);
printf("dlopen success\nresult=%d\n");
dlclose(dp);
return 0;
}
2、編譯test.c爲bin文件:
[root@loadlibrary]# gcc -c test.c
[root@loadlibrary]# gcc -o test_add -ldl test.o
生成的文件列表:
add.c
add.o
test_add
test_add.so
test.c
test.o
而test_add就是我們用來測試的bin文件了
3、執行bin文件:
執行失敗了,應該是沒找到庫的位置,臨時添加一個lib path:
[root@loadlibrary]# export LD_LIBRARY_PATH=./:LD_LIBRARY_PATH
好了,接下來就執行成功了:
[root@ loadlibrary]#./test_add
dlopen success
result=4