linux加载动态链接库so文件
linktime
有时出于软件灵活性的考虑,我们不会在编译阶段直接关联so文件,而是通过dlopen等几个函数调用动态加载,主要用到的函数接口有:
- dlopen
- dlsym
- dlclose
需要包含的头文件是 dlfcn.h ,在编译时需要加上 -ldl 。下面是一个简单的例子,首先我们写一个 lib_printnumber 函数,只是将传入的参数打印出来。
#include <stdio.h>
void lib_printnumber(int arg)
printf("lib_printnumber, argument value is: %d \n\r",arg);
}
将libtest.c文件编译成libtest.so,命令如下:
gcc -fPIC -shared libtest.c -o libtest.so
然后我们写一个call.c文件,在里面调用 lib_printnumber 函数。
#include <stdio.h>
#include <dlfcn.h>
typedef void (*libfunc)(int);
int main(int argc,int argv[])
int i;
libfunc func;
void *handler;
/* symbol稍后解析,如果不被调用则不用解析 */
handler = dlopen("./libtest.so",RTLD_LAZY);
if (handler == NULL)
printf("dlopen error!\n");
return -1;
func = dlsym(handler,"lib_printnumber");
if (func != NULL)
for (i=0;i<10;i++)
func(i);