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

混江龙づ霸主 提交于 2020-01-13 06:53:09

问题


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

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.

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

Thanks.


回答1:


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:

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

and build:

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

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.

output:

./app
and the magic number is: 1337


来源:https://stackoverflow.com/questions/17862272/dlopen-a-dynamic-library-from-a-static-library-linux-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!