做一个具备动态加载功能的需求,验证一下通过dlopen是否能够满足,结果靠谱
main文件,实际项目可以通过inotify监控lib目录是否有新增了动态库
#include "plug.h"
const char* libpath = "./libplug.so";
int main(int argc, char *argv[])
{
void* handle = dlopen( libpath, RTLD_LAZY );//RTLD_LAZY|RTLD_NOW|RTLD_GLOBAL
if( NULL == handle )
{
printf("open libplug %s err %s\n", libpath, dlerror() );
exit( EXIT_FAILURE );
}
main_plug_t main_func = (main_plug_t)dlsym( handle, "main_plug" );
printf( "main_func value %d \n", main_func(2));
dlclose( handle );
return 1;
}
编译主函数
gcc -o plug example.c -ldl
功能模块头文件,定义统一的模块入口
#include "plug.h"
//具体功能函数入口
static int function_a(int value)
{
printf("function_a value = %d\n", value);
return value + 1;
}
//定义统一的模块入口
int main_plug(int value)
{
return function_a(value);
}
gcc -o libplug.so -fPIC -shared plug.c