本文介绍了dlopen从静态库linux C ++的动态库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've a linux application that links against a static library (.a) and that library uses the dlopen function to load dynamic libraries (.so)

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

If I compile the static library as dynamic and link it to the application, the dlopen it will work as expected, but if I use it as described above it won't.

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

Can't a static library uses the dlopen function to load shared libraries?

谢谢.

推荐答案

您尝试执行的操作应该没有问题:

There should be no problem with what you're trying to do:

app.c:

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

staticlib.h:

staticlib.h:

#ifndef __STATICLIB_H__
#define __STATICLIB_H__

int doSomethingDynamicish();

#endif

staticlib.c:

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: %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();
}

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

第一行构建lib
第二行将其打包为静态lib
第三个构建测试应用程序,链接到新创建的静态文件,再加上linux动态链接库(libdl)
第四行构建了即将动态加载的共享库.

First line builds the lib
second line packs it into a static lib
third builds the test app, linking in the newly created static, plus the linux dynamic linking library(libdl)
fourth line builds the soon-to-be-dynamically-loaded shared lib.

输出:

./app
and the magic number is: 1337

这篇关于dlopen从静态库linux C ++的动态库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 10:43