GCC style weak linking in Visual Studio? GCC style weak linking in Visual Studio? c c

GCC style weak linking in Visual Studio?


You can do it, here is an example in C:

/* * pWeakValue MUST be an extern const variable, which will be aliased to * pDefaultWeakValue if no real user definition is present, thanks to the * alternatename directive. */extern const char * pWeakValue;extern const char * pDefaultWeakValue = NULL;#pragma comment(linker, "/alternatename:_pWeakValue=_pDefaultWeakValue")


MSVC++ has __declspec(selectany) which covers part of the functionality of weak symbols: it allows you to define multiple identical symbols with external linkage, directing the compiler to choose any one of several available. However, I don't think MSVC++ has anything that would cover the other part of weak symbol functionality: the possibility to provide "replaceable" definitions in a library.

This, BTW, makes one wonder how the support for standard replaceable ::operator new and ::operator delete functions works in MSVC++.


MSVC used to behave such that if a symbol is defined in a .obj file and a .lib it would use the one on the .obj file without warning. I recall that it would also handle the situation where the symbol is defined in multiple libs it would use the one in the library named first in the list.

I can't say I've tried this in a while, but I'd be surprised if they changed this behavior (especially that .obj defined symbols override symbols in .lib files).