title: Static initialization and destruction of a static library's globals not happening with g++
body: <p>Until some time ago, I thought a .a static library was just a collection of .o object files, just archiving them and not making them handled differently. But <strong>linking with a .o object and linking with a .a static library containing this .o object are apparently not the same</strong>. And I don't understand why...</p>
  
  <p>Let's consider the following source code files:</p>
  
  <pre><code>// main.cpp
  #include &lt;iostream&gt;
  int main(int argc, char* argv[]) {
      std::cout &lt;&lt; "main" &lt;&lt; std::endl;
  }
  </code></pre>
  
  <hr>
  
  <pre><code>// object.hpp
  #include &lt;iostream&gt;
  struct Object
  {
      Object() { std::cout &lt;&lt; "Object constructor called" &lt;&lt; std::endl; }
      ~Object() { std::cout &lt;&lt; "Object destructor called" &lt;&lt; std::endl; }
  };
  </code></pre>
  
  <hr>
  
  <pre><code>// object.cpp
  #include "object.hpp"
  static Object gObject;
  </code></pre>
  
  <p>Let's compile and <strong>link</strong> and run this code:</p>
  
  <pre><code>g++ -Wall object.cpp main.cpp -o main1
  ./main1
  &gt; Object constructor called
  &gt; main
  &gt; Object destructor called
  </code></pre>
  
  <p>The constructor an the destructor of the global gObject object is called.</p>
  
  <p>Now let's create a <strong>static library</strong> from our code and use (link) it in another program:</p>
  
  <pre><code>g++ -Wall -c object.cpp main.cpp
  ar rcs lib.a object.o
  g++ -Wall -o main2 main.o lib.a
  ./main2
  &gt; main
  </code></pre>
  
  <ul>
  <li><strong>gObject's constructor and destructor are not called... why?</strong></li>
  <li><strong>How to have them automatically called?</strong></li>
  </ul>
  
  <p>Thanks.</p>