简体   繁体   中英

How to mark dynamically initialized globals as "discardable if unused" in MSVC?

I have some globals like

FARPROC const f = GetProcAddress(...);

Is there any way to urge the compiler or linker to discard them (and related initialization code) if it is determined the code is unused at link-time (like with /Gy and /OPT:REF )?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM