Dlopen dynamic library from linux c ++ static library

I have a linux application that references a static library (.a), and this library uses the dlopen function to load dynamic libraries (.so)

If I compile the static library as dynamic and attach it to the application, dlopen will work as expected, but if I use it as described above, it will not.

Can a static library use the dlopen function to load shared libraries?

Thank.

+1
source share
1 answer

There should not be any problems with what you are 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

lib lib
, , linux (libdl)
lib.

:

./app
and the magic number is: 1337
+4

All Articles