您的位置:首页 > 运维架构 > Linux

linux下如何动态加载动态库(loadlibrary)

2014-03-01 09:35 302 查看


最近用到了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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: