I have following code
File hello.cc
static A dummyl; A:: A() { fun(); } void A::fun() { int y = 10; int z = 20; int x = y + z; }
File hello.h
class A { public: A a; void fun(); };
File main.cc
#include <dlfcn.h> #include "hello.h" typedef void (*pf)(); int main() { void *lib; pf greet; const char * err; printf("\n Before dlopen\n"); lib = dlopen("libhello.so", RTLD_NOW | RTLD_GLOBAL); if (!lib) { exit(1); } A *a = new A ; a->fun(); dlerror(); /*first clear any previous error; redundant in this case but a useful habit*/ dlclose(lib); return 0; }
Build phases:
- g++ -fPIC -c hello.cc
- g++ -shared -o libhello.so hello.o
- g++ -o myprog main.cc -ldl -L. -lhello
Since my shared library in real case is libQtCore.so , I need to link it as using -lQtCore
in linker because I cannot use the symbols directly and since there are many of functions then libQtCore, it will not practically advisable to use dlysym for each function of libQtCore.so
Since I link, my static global variables gets initialized before dlopen. Is there any flag for linker g++ that tells compiler to load the shared library only after _dlopen _?