GCC style weak linking in Visual Studio?

a 夏天 提交于 2019-11-26 18:49:18

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++.

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 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).

There isn't an MS-VC equivalent to this attribute. See http://connect.microsoft.com/VisualStudio/feedback/details/505028/add-weak-function-references-for-visual-c-c. I'm going to suggest something horrible: reading the purpose of it here: http://www.kolpackov.net/pipermail/notes/2004-March/000006.html it is essentially to define functions that, if their symbols exist, are used, otherwise, are not, so...

Why not use pre-processor for this purpose, with the huge caveat of "if you need to do this at all"? (I'm not a fan of recommending pre-processor).

Example:

#ifdef USE_MY_FUNCTION
     extern void function();
#endif

then call appropriately in the application logic, surrounded by #ifdef statements. If your static library is linked in, as part of the linking in process, tweak the defines to define USE_MY_FUNCTION.

Not quite a direct equivalent and very ugly but it's the best I can think of.

The only way i know. Place each symbol in a separate library. User objects with overrides also must be combined to library. Then link all together to an application. User library must be specified as input file, your lib's must be transfered to linker using /DEFAULTLIB: option.

One way of doing this would be to implement it manually via LoadLibrary and GetProcAddress.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!