Charly
Charly

Reputation: 1352

How to exclude unused methods from final binary?

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

Upvotes: 11

Views: 2782

Answers (4)

Frerich Raabe
Frerich Raabe

Reputation: 94549

After compilation the string still exist in the final binary. Why

Others have given suggestions how to get rid of that unused code in your final binary. I'd like to give some answer on the Why a bit - here are two points why it might be impossible for the function to be removed.

Unless you declared all objects of that XXX type with static linkage, the compiler cannot strip the the type (and hence the method) from the generated object file because some other object file might access the value using extern. The linker, which can see all object files at once, might be able to solve this.

However, since you tagged your question as gcc, it may be that you're not compiling and/or linking with -fvisibility=hidden. In that case, even the linker cannot strip the symbol (and hence the code) because other modules might resolve the symbol at runtime.

Upvotes: 3

ks1322
ks1322

Reputation: 35865

This is usually done by passing -ffunction-sections -fdata-sections options to gcc. Look this link for more details.

Upvotes: 7

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136515

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.

Upvotes: 8

duedl0r
duedl0r

Reputation: 9424

This is probably a really bad idea, but I have to write it anyway :) You could create a templated class, afair unused methods get removed.

Upvotes: 1

Related Questions