title: C++ static variable in .lib does not initialize
body: <p>I have static library (.lib) in VS2010 and am linking it to my test project.</p>
  
  <p>The lib has a factory that I create using the below MACRO:</p>
  
  <pre><code>#define REGISTER_FACTORY(mType, my_class) \
  class Factory##my_class : public CAbstractFactory\
  {\
  public:\
      Factory##my_class() : CAbstractFactory(mType){}\
      CBaseClass *Create()\
      { return new my_class(); }\
  };\
  static Factory##my_class StaticFactory##my_class;
  </code></pre>
  
  <p>What is supposed to happen is that in the CAbstractFactory the new factory gets registered by <code>mtype</code>. But when I check the factory the factory does not exist.</p>
  
  <p>It works fine when I use a DLL instead of a .lib. My guess is that the linker does not include the static variable as it is not referenced or the static variable was not even included in the library.</p>
  
  <p>How can I force the linker to include all objects from the static library in my .exe.</p>
  
  <p>I use the macro like this:</p>
  
  <pre><code>// Register factory that can create CMyObject with ID=100
  REGISTER_FACTORY(100, CMyObject);
  
  class CMyObject
  {
  };
  </code></pre>
  
  <p>The CAbstractFactory looks like this:</p>
  
  <pre><code>class CAbstractFactory {
      CAbstractFactory(int id) {
          CFactory::instance().add(id, this);
      }
  }
  </code></pre>
  
  <p>Then some where else in the code, my main .exe I use:</p>
  
  <pre><code>CBaseClass *pObject = CFactory::instance().Create(100);
  </code></pre>
  
  <p>This will then give my a new <code>CMyObject</code>. The idea is that I have many different kind object and I have a database containing the id specifying the kind of objects I need.
  <code>100</code> is just an example.</p>
  
  <p>So indeed, I do not reference anything from the .lib directly but I want to be able to create the objects using my factory</p>
  
  <p>The CFactory class is a simple class that keeps a register (in a map) of all the CAbstractFactory classes and delegates the create method to the correct factory.</p>
  
  <pre><code>CFactory &amp;CFactory::Instance()
  {
      static CFactory instance;
      return instance;
  }
  </code></pre>
  
  <p>The main problem lies in the fact that I do not reference anything from the .lib as it is all done through the CFactory. It works if I make it a DLL and make sure I add some reference to this DLL to make sure it is loaded. But for a .lib, I even added a dummy function to make sure I have at least one reference that doesn't include the rest of the code.</p>