c++visual-studio-2010visual-c++macros

What causes a TU to be included in compilation?


I am a little out of my depth here, I'll be honest.

I am doing some rather curious experimentation, having pre-main functions register my classes in a factory, through anonymous namespaces. Until recently, adding the following to a class definition (.cpp) would do the trick.

namespace { int x = Register<classType>(className); }

This would be wrapped in a macro and 'Register' would pass the type and name off to my factory.

This worked fine and every class that included this macro was getting registered, until I went to move the code into a static library. Now, since the classes are only referenced by the factory, it looks like they're being omitted from the build - my 'Register' functions are no longer being called and so my factory is empty.

I have managed to fix this by moving all my macros into the constructor of a manager object, but I noticed that as soon as I referenced them there, the macros in the .cpp files started getting called again. I guessed because now the classes are actually being referenced by something.

However, I don't really want to do it this way and I can't seem to find a non-committal way of referencing the classes in the constructor (e.g class ClassToRegister;) which includes them in the build, so that my register macros will get called.

Firstly, does this make sense?

Secondly, any advice on how I can force these TUs to compile so that the anonymous namespaces 'kick in' at runtime?


Solution

  • It appears this is part and parcel of using static libraries; unused code will not make it through without linker voodoo.