eliminate unused virtual functions

2019-01-26 19:56发布

问题:

To eliminate unused (ordinary) function I can use: -ffunction-sections, -fdata-section and --gc-sections. and it works.

I know that using polymorphism, function are 'late-binding' so I suppose there is no way to decide which of the function can be remove during linkage process.

But I am using pure virtual function to force class which inherits to implement some function. Then in code I am using objects (not pointer/reference to object, so I am not using polymorphism).

pseudo code:

class BASE {
    ...
    virtual void do_sth() = 0;
    virtual void do_sth_else() = 0;
    ...
};

class C1 : BASE {
    ...
    void do_sth() { //some code }
    void do_sth_else() { //some code }
}

main()
{
    //the do_sth_else function is never used in main
    C1 obj1;
    obj.do_sth();
}

Is there some method to eliminate this unused functions (do_sth_else) during linkage process? Maybe I misunderstood something. and because of that I think there should be a way to remove this unused function. If so please explain me why, when I am NOT using pointers with virtual function there is no way to "get rid" of polymorphic overhead. :)

FYI: This code is mainly for learning purpose.

回答1:

Thanks to Jonathan Wakely I started digging and I found gcc options:

-fvtable-gc Emit special relocations for vtables and virtual function references so that the linker can identify unused virtual functions and zero out vtable slots that refer to them. This is most useful with -ffunction-sections and -Wl,--gc-sections, in order to also discard the functions themselves.

But it is not supported in GCCv4.7.1



回答2:

For learning purpose I suggest you to learn the semantics of language elements and learn to use them for their purpose. I.e. use virtuals there yo want polymorphism and leave them alone otherwise.

Worrying about things like the amount of dead code left in by the linker can be safely left to 5-10 years ahead or forever.

And optimization improves every year, so even if today yo could find 0.01% of the image as possible waste by the time you get to production it may be gone just by itself.