简体   繁体   中英

Remove unreferenced global variables from statically linked libraries

I have a global class the equivalent of this:

class CUnref
{
public:
    CUnref() : a(42), b(999)
    {
    }
    virtual ~CUnref()
    {
    }
    int a, b;
};
CUnref Unref;

I want the global variable Unref to be removed from the final executable if it is not referenced.

In my specific case I have a collection of such global helpers to assist in enum<->string conversion in a separate statically linked library. This stackoverflow 's answers seem to indicate that these unused global instances should not be linked in the final executable in the specific case of statically linked libraries. Inspecting the generated executable shows the instance and related symbols are still present..

Removing the virtual functions makes it disappear from the final executable (basically making the global unreferenced class POD) but I really need inheritance. I do not perform any side effects (such as allocating memory) or anything, just inheritance.

How do I make sure these unreferenced global variables (of non-POD type but without side effects) are not linked in the final executable?

Compiler is whatever comes with visual studio 2012.

Solution provided by How to prevent VC++ 9 linker from linking unnecessary global variables?

In msvc mark the globals with __declspec(selectany) will make the linker remove them if they are unreferenced.

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