c++ - 消除未使用的虚函数

标签 c++ gcc linker virtual-functions

为了消除未使用的(普通)函数,我可以使用: -ffunction-sections、-fdata-section 和 --gc-sections。 并且有效。

我知道使用多态性,函数是“后期绑定(bind)”的,所以我想没有办法决定在链接过程中可以删除哪个函数。

但我正在使用纯虚函数来强制继承的类实现某些功能。然后在代码中我使用对象(不是对象的指针/引用,所以我没有使用多态性)。

伪代码:

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();
}

有没有什么方法可以在链接过程中消除这些未使用的函数(do_sth_else)? 也许我误解了什么。因此,我认为应该有一种方法可以删除这个未使用的功能。如果是这样,请解释为什么,当我不使用带有虚函数的指针时,没有办法“摆脱”多态开销。 :)

仅供引用:此代码主要用于学习目的。

最佳答案

感谢Jonathan Wakely我开始挖掘并找到了 gcc 选项:

-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.

但在GCCv4.7.1中不支持

关于c++ - 消除未使用的虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17433791/

相关文章:

c++ - 可执行 VC++ 中的奇怪字符串

c++ - 如何处理类中的动态分配变量?

c++ - 如何使用 CZMQ-4.0.2 新的 zsock API 创建发布/订阅架构?

linux - 如何将 -std=c++11 添加到我的 Qt Creator 中的编译器选项?

c - 移植 InterlockedExchange,仅使用 GCC 内部函数

iphone - 使用发布版本有效测试 iPhone 应用程序

c++ - DllGetClassObject 返回 "No such interface supported"而 CoCreateInstance 可以找到它成功

ubuntu - 如何为 ubuntu 16.04 安装 gcc 7.3?

c - 在 Linux 上使用共享库来减少内存负载

c - ld: 找不到 lc -错误