Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 209
user2662514 Avatar asked Aug 07 '13 23:08

user2662514


People also ask

Does linker remove unused functions?

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.

Which of the following options is necessary to create a shared library?

The -shared or -dynamiclib option is required to create a shared library.


1 Answers

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.

like image 51
Dietrich Epp Avatar answered Oct 23 '22 21:10

Dietrich Epp