0

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 .

chandran
  • 69
  • 1
  • 7
  • 1
    Is it possible that it gets called **before** the constructor of lib::Obj? – user253751 Mar 25 '22 at 17:43
  • Make `Obj` static inside `getInstance` rather than class-static. – n. m. could be an AI Mar 25 '22 at 19:26
  • Hi, Making Obj static inside getInstance() works. Thanks for your input. But any reason why it's not working if i keep it as class static. The reason why i put as class static is, in similar way it was handled in some of the libraries in my project. Do you think its related to construction initialisation order /priority during startup? – chandran Mar 25 '22 at 23:58
  • Hi, This post actually helped. https://stackoverflow.com/questions/43941159/global-static-variables-initialization-issue-with-attribute-constructor-i. To force initalization of static objects __attribute__ ((init_priority(101))) is needed. Thanks – chandran Mar 26 '22 at 06:39

0 Answers0