I have a code that I need to compile to shared library and remove ALL unused code from, but I can't find a proper solution. Here is a simple example:
// 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
makes it so that all functions are hidden by default, and I manually mark public functions with __attribute__((visibility("default")))
. However, hidden functions are not removed unless marked as static
(which I can't do to C++ methods, obviously).
No matter what I do, GCC will always keep void Foo::bar()
and hello
around. Is there a way to remove these symbols without hacking the compiler? (yes, I am considering it at this point!)
Thanks!
So the linker is able to remove each individual function because it is in its own section. So enabling this for your library will allow the linker to remove unused functions from the library.
The -shared or -dynamiclib option is required to create a shared library.
Compile with the flag -ffunction-sections
. Then link with -Wl,--gc-sections
. I think that this can also be achieved with LTO, I'm not sure of the details.
Note that all public symbols in a dylib are considered live. Only hidden symbols will be stripped this way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With