I figured it out. It seems __declspec(selectany)
does this, even without passing /Gw
.
As an example, this program will only contain GetTickCount_
:
#include <Windows.h>
FARPROC GetTickCount_ =
GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")), "GetTickCount");
__declspec(selectany) FARPROC GetTickCount64_ =
GetProcAddress(GetModuleHandle(TEXT("Kernel32.dll")), "GetTickCount64");
int main()
{
}
For a cross-platform soluition, use static
variables in template classes. They are discarded if unused, even if the initializer has side effects.
Example:
#include <cstddef>
#include <iostream>
template <std::nullptr_t = nullptr>
struct A
{
inline static const int value = []{
std::ios_base::Init init;
std::cout << "Hello, world!\n";
return 42;
}();
};
int main()
{
// Nothing is printed, unless you uncomment following:
// (void)A<>::value;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.