duplicate singleton on Windows-platform

Chris Bielow bielow@mi.fu-berlin.de
Wed Feb 6 19:07:00 GMT 2008


Hi,

I'm having trouble creating a "real" singleton on Windows (MinGW 
Binutils 2.18) when linking my the executable against the shared version 
my library (all C++). Under Linux everything is fine.
The Singleton is a static member of template class.

------------- Factory.h ----------------
template <typename FactoryProduct>
class Factory
{
   static Factory* instance()
   {
     if (!instance_ptr_)
     {
       std::cout << "INITIALIZING ... "
       instance_ptr_ = new Factory();
       FactoryProduct::registerChildren();
     }
     return instance_ptr_;
   }

   ...

private:

  static Factory* instance_ptr_;
}
template<typename FactoryProduct> Factory<FactoryProduct>* 
Factory<FactoryProduct>::instance_ptr_ = 0;

----------- END Factory.h ---------

The Factory.h header is included in some of the classes (**) that are 
compiled into the shared library.

Now, if I write a test program that uses this library, there seem to be 
multiple instances, as I get :

INITIALIZING ...
INITIALIZING ...

, which does NOT happen when linking the executable with the static 
version of the library.
btw: The test program also includes the Factory.h header, because it 
contains something like:
----------- Test.Cpp -----------
DataReducer* p = Factory<DataReducer>::create("max_reducer");
----------- END Test.Cpp -----------

If use the following commands to create the library under Windows:

dynamic:
/mingw/bin/g++ -Wl,--export-dynamic -shared -o libOpenMS.dll \
     -Wl,--export-all-symbols \
     -Wl,--enable-auto-import \
     -Wl,--whole-archive <list of objects to add> \
     -Wl,--no-whole-archive <other dependent libs> \
     -Wl,--large-address-aware

static:
/mingw/bin/ar cru libOpenMS.a <list of objects to add>

under linux something like:
/usr/bin/g++ -shared -fPIC -o libOpenMS.so <list of objects to add> -lm

does suffice (and it works).

So, to summarize:

Linux
  -static (.a): OK
  -dynamic(.so): OK
Windows (MinGW)
  -static (.a): OK
  -dynamic(.dll): FAILED - why?



Any ideas why that happens?

thanks!
cheers
Chris



More information about the Binutils mailing list