title: Linux shared library init & deinit when also using c++ static initializer
body: <p>I want to have automated calls to initialize and deinitialize my shared library.</p>
  
  <p>In my shared library, I need some static initialization of C++ objects, among others because of use of third party code (e.g. UnitTest++).
  When my init function is executed, I need to be guaranted, that all static initialization of C++ objects (of all linked translation units) is done (and vice versa for deinit); so just the same conditions as the execution of main() can expect in a C++ program.</p>
  
  <p>I've seen much informations about linux shared library init/deinit e.g. like:<ul>
  <li><a href="https://stackoverflow.com/questions/9759880/automatically-executed-functions-when-loading-shared-libraries">Automatically executed functions when loading shared libraries</a></li>
  <li><a href="https://stackoverflow.com/questions/1681145/how-to-initialize-a-shared-library-on-linux">How to initialize a shared library on Linux</a></li>
  <li><a href="http://www.faqs.org/docs/Linux-HOWTO/Program-Library-HOWTO.html#INIT-AND-CLEANUP" rel="nofollow noreferrer">http://www.faqs.org/docs/Linux-HOWTO/Program-Library-HOWTO.html#INIT-AND-CLEANUP</a></li>
  </ul>
  But the provided solutions won't fit my needs. In both approaches (<code>__attribute__((constructor))</code> and even <code>-Wl,-init,&lt;function name&gt;</code>) the init function seems to be called before static initialization of C++ objects is completely done.</p>
  
  <p>I also played around with <code>__attribute__ ((init_priority(…)))</code> like:</p>
  
  <pre><code>class InitAndDeinit {
  public:
      InitAndDeinit() {
          // Do some initialization
      }
      ~InitAndDeinit() {
          // Do some cleanup
      }
  } initAndDeinit __attribute__((init_priority(65535)));
  </code></pre>
  
  <p>But that also won't place the calls to the desired point; even with <code>__attribute__((constructor(65535)))</code>.</p>
  
  <p>I'd tested with gcc 4.6.4, 4.7.3 and 4.8.1 (4.6.4 shows a slightly different behaviour regarding the sorting of <code>__attribute__((constructor))</code>).</p>
  
  <p>Any suggestions?</p>
  
  <p>My current workaround is to provide exported functions (lib_init() and lib_deinit()) which have to called manually by the application.</p>