Tuesday, September 21, 2010

Aliasing symbol names during Link time

Reference: see  VC/crt/src/crtdll.c




  /*
  * _pRawDllMain MUST be an extern const variable, which will be aliased to
  * _pDefaultRawDllMain if no real user definition is present, thanks to the
  * alternatename directive.
  */

extern BOOL (WINAPI * const _pRawDllMain)(HANDLE, DWORD, LPVOID);
extern BOOL (WINAPI * const _pDefaultRawDllMain)(HANDLE, DWORD, LPVOID) = NULL;
#if defined (_M_IX86)
#pragma comment(linker, "/alternatename:__pRawDllMain=__pDefaultRawDllMain")
#elif defined (_M_IA64) || defined (_M_AMD64)
#pragma comment(linker, "/alternatename:_pRawDllMain=_pDefaultRawDllMain")
#else  /* defined (_M_IA64) || defined (_M_AMD64) */
#error Unsupported platform
#endif  /* defined (_M_IA64) || defined (_M_AMD64) */

Example:
1. Inside a static lib A, put the following
extern "C" int xxx = 2;
2. Inside an EXE which links A, put the following
extern "C" int a = 4;
#pragma comment(linker, "/alternatename:_xxx=_a")

In this case "xxx" will be resolved as 2. Now how if we remove the line inside static-lib A. In this case the linker will replace "xxx" with "a", which is equal to 4.


BTW, don't forget to put addition "_" in front of symbol name inside #pragma comment directives. It is necessary to follow "C" name decoration. See http://msdn.microsoft.com/en-us/library/deaxefa7.aspx.

No comments:

Post a Comment