title: C++ global variable not initialized when linked through static libraries, but OK when compiled with source
body: <p>I have created a system that automatically registers function objects (functors) into a map based on the constructor of an global instance.</p>
  
  <p>In each cpp file that defines the functor, there's a global instance of the registrar class instance to register the functor to a singleton <code>std::map&lt;int, std::function&lt;...&gt; &gt;</code> object.</p>
  
  <p>This is the definition of registrar class:</p>
  
  <pre><code>template
  &lt;
      typename map_type,
      typename handler_type
  &gt;
  struct registrar
  {
      registrar
          (
               map_type&amp; map_object,
               boost::uint16_t cmd_code,
               const handler_type&amp; handler
          )
          {
            map_object.insert(std::pair&lt;boost::uint16_t, handler_type&gt;(cmd_code, handler));
          }
  };
  </code></pre>
  
  <p>in each .cpp file.  The global instance is defined like this:</p>
  
  <pre><code>namespace one_way
  {
      static registrar &lt;in_out_map_type, handler&gt;
          post_receiver(in_out_map_type::instance(), command, handlers());
  }
  </code></pre>
  
  <p>All works fine if I compile all the cpp with the main.cpp together. But If I compile the cpp file into a static library and link it to <code>main.cpp</code>, the registration does not work.</p>
  
  <p>I tested with VC10 and GCC4.61 both on Windows &amp; and Ubuntu 11.10. Both fail.</p>
  
  <p>I found <a href="http://www.gamedev.net/topic/427438-variable-initialization-across-static-libraries/">a thread with the same problem</a> but OP did not say whether he solved it or not.</p>
  
  <p>Am I missing anything?</p>
  
  <hr>
  
  <p><strong>Edit</strong></p>
  
  <hr>
  
  <p>Thanks for all responses including the comments. </p>
  
  <p>Every response indeed helped me to think more and investigate deep into this method. After all the study and trials, I finally gave up the idea of relying on global/static variable for self-registration <strong><em>across binary boundaries</em></strong>, because there's no <strong><em>portable</em></strong> way to guarantee it will work. </p>
  
  <p>My final way is to keep the registration within one binary.</p>