Re: Global and file-static variables in static library
"Ben Voigt [C++ MVP]" <rbv@nospam.nospam> wrote in message
news:247E1A1D-8059-479C-9E6E-84A713C4A559@microsoft.com...
It just seems that when .obj files are in a static library, the linker
eliminates stuff more aggressively than when they are stand-alone. This
is reasonable perhaps, because otherwise a static library might
contribute a lot of dead code. But it is a real PITA. What is needed,
perhaps, is some kind of FORCE keyword in the language that requires a
variable or class object to be initialized before main(), which seems to
be the default in all known compilers in the absence of static libraries
(though not, it seems, required by the standard).
Have you tried:
#pragma comment(linker, "/include:__mySymbol")
as mentioned in http://msdn2.microsoft.com/en-us/library/ms879989.aspx
.... and not that to use this neat trick, you need to supply the mangled C++
name for the symbol. you can avoid that by including an extern "C" function
in the same module, and reference that function (with it's relatively
unmangled name) instead of your anonymous namespace scoped variable (which
will have a truly awful name).
Something like this:
// D1.h
#pragma comment(linker,"/include: _InitD")
class D1: public Base
{
public:
D1();
// declare virtual overrides
};
//--------------------------------------------------
// D1.cpp
#include "D1.h"
namespace
{
Base* Create(){return new D1;}
bool auto_register = RegisterPlugin("D1", Create);
}
D1::D1(){}
// virtual function definitions for D1
extern "C" __cdecl InitD()
{
}
-cd