从静态库linux C++中打开一个动态库

dlopen a dynamic library from a static library linux C++

本文关键字:一个 动态 linux 静态 C++      更新时间:2023-10-16

我有一个linux应用程序,它链接到一个静态库(.a),该库使用dlopen函数加载动态库(.so)

如果我将静态库编译为动态库并将其链接到应用程序,那么dlopen-it将按预期工作,但如果我如上所述使用它,则不会。

静态库不能使用dlopen函数加载共享库吗?

谢谢。

您尝试做的事情应该没有问题:

app.c:

#include "staticlib.h"
#include "stdio.h"
int main()
{
  printf("and the magic number is: %dn",doSomethingDynamicish());
return 0;
}

staticlib.h:

#ifndef __STATICLIB_H__
#define __STATICLIB_H__
int doSomethingDynamicish();
#endif

staticlib.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: %sn",dlerror());
    return 0;
  }
  typedef int(*dynamicfnc)();
  dynamicfnc func = (dynamicfnc)dlsym(handle,"GetMeANumber");
  const char* err = dlerror();
  if(err)
  {
    printf("could not dlsym: %sn",err);
    return 0;
  }
  return func();
}

dynlib.c:

int GetMeANumber()
{
  return 1337;
}

和构建:

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

第一行构建库
第二行将其打包到静态库中
第三个构建测试应用程序,在新创建的static和linux动态链接库(libdl)中进行链接
第四行构建即将动态加载的共享lib。

输出:

./app
and the magic number is: 1337