Linux下動態加載動態庫,更新動態庫而不用更新程序
linux下動態加載動態庫,主要用到dlopen(),dlsym(),dlclose(),dlerror()四個函數,他們所使用的頭文件#include <dlfcn.h>在這里主要介紹一下dlopen()函數
dlopen() 功能:打開一個動態鏈接庫
包含頭文件:
#include <dlfcn.h>
函數定義:
void * dlopen( const char * pathname, int mode );
函數描述:
在dlopen的()函數以指定模式打開指定的動態連接庫文件,并返回一個句柄給調用進程。使用dlclose()來卸載打開的庫。
mode:分為這兩種
RTLD_LAZY 暫緩決定,等有需要時再解出符號
RTLD_NOW 立即決定,返回前解除所有未決定的符號。
RTLD_LOCAL
RTLD_GLOBAL 允許導出符號
RTLD_GROUP
RTLD_WORLD
返回值:
打開錯誤返回NULL
成功,返回庫引用
編譯時候要加入 -ldl (指定dl庫)
例如
gcc test.c -o test -ldl
下面舉個例子,同時考慮到幾個細節。
#include<stdio.h>
#include<dlfcn.h>
int main()
{
int a,b;
void *pHandle;
pHandle=dlopen("./dl2.so",RTLD_NOW);
{
cerr << "Cannot open library: " << dlerror() << ' ';
return 1;
}
func=(func)dlsym(pHandle,"max");
if (dlsym_error) {
cerr << "Cannot load symbol 'baidu': " << dlsym_error <<' ';
dlclose(pHandle);
return 1;
}
printf("%d與%d相比,%d為大數。\n",a,b,(*func)(a,b));
dlclose(pHandle);
}
/***********************main.c的內容**************************/
/***********************testmax.c的內容**************************/
#include<stdio.h>
int max(int x,int y)
{
return x>y?x:y;
}
/***********************testmax.c的內容**************************/
編譯:
gcc testmax.c -shared -fPIC -o testmax.so
gcc -o main -ldl main.c
運行:
admin@admin-desktop:/abc/test$ ./main
2008 2012
2008與2012相比,2012為大數。
很淺層的東西,這樣下次你直接修改你的testmax.c文件,編譯成動態庫拷貝到main目錄,不用編譯,直接可以加載你最新修改的testmax中的函數,前提是函數名、格式要相同。

