问题描述
我有一些像
这样的全局变量FARPROC const f = GetProcAddress(...);
如果确定代码在链接时未使用(例如 /Gy
和 /OPT:REF
),是否有任何方法可以促使编译器或链接器丢弃它们(以及相关的初始化代码)?
解决方法
我想通了。似乎 __declspec(selectany)
做到了这一点,即使没有通过 /Gw
。
举个例子,这个程序将只包含GetTickCount_
:
#include <Windows.h>
FARPROC GetTickCount_ =
GetProcAddress(GetModuleHandle(TEXT("kernel32.dll")),"GetTickCount");
__declspec(selectany) FARPROC GetTickCount64_ =
GetProcAddress(GetModuleHandle(TEXT("Kernel32.dll")),"GetTickCount64");
int main()
{
}
,
对于跨平台解决方案,请在模板类中使用 static
变量。如果未使用,即使初始化器有副作用,它们也会被丢弃。
示例:
#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;
}