How to force inclusion of static objects from a static library in C ++ (MSVC 11)

I am trying to initialize a static object in a C ++ file that is trying to automatically register a class in a factory in its constructor (for example, any standard problem of automatic registration). The problem is that this is compiled into a static library and when linking to an executable that is optimized. It must have been a very simple solution, but surprisingly, it seems like it is not so simple.

Here is my class:

In Factory.h (part of the static lib project)

class DummyClass : public BaseFactoryClass { int mDummyInt; public: DummyClass() { std::cout << "Pretending to register myself to the factory here\n"; } }; 

In some cpp let's say Circle.cpp (still part of the static lib project)

 static DummyClass dum; 

main.cpp (part of the executable file)

 //some code accessing the BaseFactoryClass of the Registered derived classes. 

Now, since the static object is not used directly in the executable project, it is skipped from the linked library.

I want it to work in MS VC11 (Visual Studio 2012) (and GCC 4.8. *, But this is for later). Looking at other issues, I have tried different things so far that don't seem to work:

  • It seems that the WHOLEARCHIVE link option is only supported with Visual Studio 2015 (we are using VS 2012)
  • The task / OPT: NOREF should have worked (I tried several combinations of this with other flags, for example / OPT: NOICF), but it does not work for anyone.
  • I tried #pragma comment (linker, "/ include: symbolName") in the header file, but this gives the linker error about not recognizing the character. (Also, this would not work in GCC, but probably the whole archive works there).

There is a flag in the settings of the Visual Studio linker that allows you to link all object files individually, and not a static library, but I do not want to go along this route. In addition, it is advisable to simply write something in the source (.cpp) of each individual class that I want to automatically register, and all boiler plate code and macros are in the central header, for example BaseFactory.h, etc. Is there any way to do this (even in C ++ 11 where there is a guarantee that the character will be initialized)? Want to make registering a new class as simple as possible for any new developer.

0
c ++ static linker visual-studio-2012 static-linking
Sep 05 '16 at 19:43
source share
1 answer

In MSVC, you have a linker pragma that you can use for this purpose:

 #pragma comment (linker, "/export:_dum") 

Thus, whenever the linker starts, it forces _dum in your executable or DLL.

However, it would be better to consider using a DLL instead of a static library. Then you will completely avoid this problem, because with each loading of the DLL this static variable will be initialized.

0
Apr 19 '19 at 18:22
source share



All Articles