I am trying to created a shared library in c++ and to initialize the library i define a function with __attribute__ ((constructor)) , but this function is not at all getting invoked.
Any idea why __attribute__ ((constructor)) is not getting called here?
lib.h file
#include <iostream>
using namespace std;
class lib {
public:
int i=0;
lib() { i=5; }
~lib() { cout << "calling lib destructor" << endl; }
static lib* getInstance();
void set() { i=i+25; }
int get() { return i; }
private:
static lib Obj;
};
lib.cpp
#include "lib.h"
lib lib::Obj;
lib* lib::getInstance()
{
return &Obj;
}
void __attribute__ ((constructor)) init_fn(void) ;
void init_fn(void)
{
lib::getInstance()->set();
}
i am creating a shared object using below command
g++ -Wall -Wextra -fPIC -shared lib.cpp -Wl,-soname,libfoo.so -o libfoo.so
Once shared library is created , i am linking it with a main program
main.cpp
#include <iostream>
#include "lib.h"
using namespace std;
int main()
{
cout << lib::getInstance()->get() << endl; // Expecting a output of 30, but always getting 5
cout << "End of program" << endl;
return 0;
}
g++ -L./ -Wall -o main main.cpp -lfoo (linking with shared object libfoo.so)
output:
./main
5
End of program
calling lib destructor
init_fn() function with constructor attribute is not at all getting invoked during loading of the shared object libfoo.so. Tried on various c++ compilers (clang and g++), but i am not able to make it work. Anything i am doing wrong while creating shared object? Please help me .