Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude unused methods from final binary?

Tags:

c++

gcc

I thought that private methods, which are not used inside its class are removed by the compiler/linker and would not be part of the final binary.

I have created an example class, with a private method which is implemented but not used.

class XXX
{
  public:
  XXX();

  private:
  void MyUnusedMethod();
};

And in the implementation file:

void XXX::MyUnusedMethod()
{
  const char* hugo = "ABCCHARLYABC";
  printf( hugo );
}

After compilation the string still exist in the final binary. Why? And how can I prevent this?

Best regards, Charly

like image 518
Charly Avatar asked Aug 09 '11 08:08

Charly


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.

Do unused functions get compiled?

Yes: for unused static functions.

Do unused variables affect performance Javascript?

Unused local variables make code hard to read and understand. Any computation used to initialize an unused variable is wasted, which may lead to performance problems.


1 Answers

One portable way is to have a .o file for each function. Then build an archive .a from those .o files. When linking against that archive the linker links in only those .o files that resolve symbols, i.e. the .o files with a function that nobody calls are not linked in.

Another way is to use latest versions of gcc with link-time code generation.

like image 157
Maxim Egorushkin Avatar answered Oct 23 '22 12:10

Maxim Egorushkin