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

How to remove *ALL* unused symbols from a shared library?

本文关键字:ALL 符号 未使用 删除 共享      更新时间:2023-10-16

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

// 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。有没有一种方法可以在不侵入编译器的情况下删除这些符号?(是的,我现在正在考虑!)

谢谢!

使用标志-ffunction-sections编译。然后与-Wl,--gc-sections链接。我认为LTO也可以实现这一点,我不确定细节。

请注意,dylib中的所有公共符号都被视为活动符号。只有隐藏的符号才会以这种方式被剥离。