Ped*_*lva 2 c++ linux static-libraries dlopen
我有一个链接静态库 (.a) 的 linux 应用程序,该库使用 dlopen 函数加载动态库 (.so)
如果我将静态库编译为动态库并将其链接到应用程序,则 dlopen 它将按预期工作,但如果我如上所述使用它,则不会。
静态库不能使用 dlopen 函数加载共享库吗?
谢谢。
您尝试执行的操作应该没有问题:
应用程序.c:
#include "staticlib.h"
#include "stdio.h"
int main()
{
printf("and the magic number is: %d\n",doSomethingDynamicish());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
静态库.h:
#ifndef __STATICLIB_H__
#define __STATICLIB_H__
int doSomethingDynamicish();
#endif
Run Code Online (Sandbox Code Playgroud)
静态库.c:
#include "staticlib.h"
#include "dlfcn.h"
#include "stdio.h"
int doSomethingDynamicish()
{
void* handle = dlopen("./libdynlib.so",RTLD_NOW);
if(!handle)
{
printf("could not dlopen: %s\n",dlerror());
return 0;
}
typedef int(*dynamicfnc)();
dynamicfnc func = (dynamicfnc)dlsym(handle,"GetMeANumber");
const char* err = dlerror();
if(err)
{
printf("could not dlsym: %s\n",err);
return 0;
}
return func();
}
Run Code Online (Sandbox Code Playgroud)
dynlib.c:
int GetMeANumber()
{
return 1337;
}
Run Code Online (Sandbox Code Playgroud)
并构建:
gcc -c -o staticlib.o staticlib.c
ar rcs libstaticlib.a staticlib.o
gcc -o app app.c libstaticlib.a -ldl
gcc -shared -o libdynlib.so dynlib.c
Run Code Online (Sandbox Code Playgroud)
第一行构建lib
第二行打包成静态lib
第三行构建测试应用程序,链接新创建的静态,加上linux 动态链接库(libdl)
第四行构建即将动态加载的共享库.
输出:
./app
and the magic number is: 1337
Run Code Online (Sandbox Code Playgroud)