dlopen 使用范例

库代码:

#include <stdio.h>
void hello(void)
{
    printf(
"hello\n");
}

编译命令:

gcc -shared -o hello.so hello.c

使用库的代码:

代码
#include <stdio.h>
#include 
<stdlib.h>
#include 
<dlfcn.h>

int main(int argc, char **argv)
{
    
void *handle;
    
void (*callfun)();
    
char *error;
    handle 
= dlopen("/root/tmp/hello.so",RTLD_LAZY);  //如果hello.so不是在LD_LIBRARY_PATH所申明
                                                      
//的路径中必须使用全路径名
    if(!handle)
    {
        printf(
"%s \n",dlerror());
        exit(
1);
    }
    dlerror();
    callfun
=dlsym(handle,"hello");
    
if((error=dlerror())!=NULL)
    {
        printf(
"%s \n",error);
        exit(
1);
    }
    callfun();
    dlclose(handle);
    
return 0;
}

编译命令:

 gcc -o hello_dlopen hello_dlopen.c -ldl

 执行:./hello_dlopen

从中可以体会到编译时不需要库的好处。另外一种在编译的时候需要动态库的使用方法:

http://www.cnblogs.com/leaven/archive/2010/06/11/1756294.html

原文地址:https://www.cnblogs.com/leaven/p/1947180.html