如何在 MSVC 中将动态初始化的全局变量标记为 "discardable if unused"?
How to mark dynamically initialized globals as "discardable if unused" in MSVC?
我有一些全局变量,比如
FARPROC const f = GetProcAddress(...);
对于跨平台解决方案,请在模板 类 中使用 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;
}
我明白了。好像是__declspec(selectany)
does this, even without passing /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()
{
}
我有一些全局变量,比如
FARPROC const f = GetProcAddress(...);
对于跨平台解决方案,请在模板 类 中使用 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;
}
我明白了。好像是__declspec(selectany)
does this, even without passing /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()
{
}