title: In c++ , shared library function with __attribute__ ((constructor)) not getting invoked during loading of the library
body: <p>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.</p>
  <p>Any idea why __attribute__ ((constructor)) is not getting called here?</p>
  <pre><code>lib.h file
  
  #include &lt;iostream&gt;
  using namespace std;
  class lib {
      public:
         int i=0;
         lib() { i=5; }
         ~lib() { cout &lt;&lt; &quot;calling lib destructor&quot; &lt;&lt; endl; }
  
          static lib* getInstance();
  
          void set() { i=i+25; }
          int get() { return i; }
      private:
          static lib Obj;
  };
  
  lib.cpp
  
  #include &quot;lib.h&quot;
  
  lib lib::Obj;
  lib* lib::getInstance()
  {
      return &amp;Obj;
  }
  
  void __attribute__ ((constructor)) init_fn(void) ;
  
  void init_fn(void)
  {
       lib::getInstance()-&gt;set();
  }
  </code></pre>
  <p>i am creating a shared object using below command</p>
  <p><em><strong>g++ -Wall -Wextra -fPIC -shared  lib.cpp -Wl,-soname,libfoo.so -o libfoo.so</strong></em></p>
  <p>Once shared library is created , i am linking it with a main program</p>
  <pre><code>main.cpp
  
  #include &lt;iostream&gt;
  #include &quot;lib.h&quot;
  using namespace std;
  
  
  int main()
  {
     cout &lt;&lt; lib::getInstance()-&gt;get() &lt;&lt; endl;   // Expecting a output of 30, but always getting 5
     cout &lt;&lt; &quot;End of program&quot; &lt;&lt; endl;
     return 0;
  }
  </code></pre>
  <p><em><strong>g++ -L./  -Wall -o main main.cpp -lfoo</strong></em> (linking with shared object libfoo.so)</p>
  <h1>output:</h1>
  <p>./main</p>
  <p>5</p>
  <p>End of program</p>
  <p>calling lib destructor</p>
  <p>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 .</p>