Search code examples
c++functioncompiler-constructionlinkeroverhead

Overhead in unused code


I am wondering what the overhead is of having unused functions in your code.

Say for example you have some debug logging, and you then give most of your objects a ToString() function that is being used in the debug logs.

In a release build that debug logging is not being used. Is it then worth it removing the source code of those ToString() functions? (e.g. via Macro?)

Or do they just make the executable marginally larger and otherwise don't impact performance? e.g. no speed impact? Or does the compiler or linker possibly even remove the functions if they are not used? If the compiler or linker don't remove the code, what if the ToString() functions were defined inline? Presumably it would try to inline the code, and since the function is never called, it would disappear?

I imagine every function needs to be retained in a static lib, but once compiled to an executable, surely a lot of stuff just gets ignored by the linker?

On another note that is roughly similar, if the compiler chooses not to inline an inline function, so that the inline function is defined as function in several compilation units, will the linker chuck away the superfluous definitions and only link one of them at the end?

Thanks


Solution

  • It depends on the compiler and, I guess, optimization level.

    G++ and MSVC++ remove unused inline functions but keep unused non-inline functions. For instance, you use only a small fraction of the STL in a normal program. All unused functions get removed, because they're defined as inline.

    GCC on the other hand keeps all functions, even unused inline ones.

    Answer to your other question: if a function is somehow defined in multiple compilation units, the linker will frown and refuse to link, unless if it is defined as inline.