如何从共享库中删除* ALL *未使用的符号?

时间:2013-08-07 23:40:03

标签: c++ c shared-libraries

我有一个代码,我需要编译到共享库并删除所有未使用的代码,但我找不到合适的解决方案。这是一个简单的例子:

// test.cpp, compiled with GCC -fPIC -shared -fvisibility=hidden
#include <stdio.h>
class Foo {
    void bar();
};
void Foo::bar() { printf("hello"); } // unused and should be removed
// I'm using printf("hello") so I can detect the symbols with `strings`

__attribute__((visibility("default"))) void test() {} // this function is "used"

-fvisibility=hidden使默认情况下隐藏所有函数,并使用__attribute__((visibility("default")))手动标记公共函数。但是,除非标记为static(显然我无法对C ++方法做),否则不会删除隐藏的函数。

无论我做什么,GCC都会始终保持void Foo::bar()hello。有没有办法在不破坏编译器的情况下删除这些符号? (是的,我现在正在考虑它!)

谢谢!

1 个答案:

答案 0 :(得分:6)

使用标记-ffunction-sections进行编译。然后链接到-Wl,--gc-sections。我认为这也可以通过LTO实现,我不确定细节。

请注意,dylib中的所有公共符号都被视为实时符号。只有隐藏的符号才会被剥离。

相关问题