Reputation: 2931
Just some opitmization considerations:
Does anyone know it for sure whether intel C++ compiler (such as ICC 13.0, and of cause, compiled with some optimzation options like /O3 etc) will automatically optimize out any unused/uncalled struct/class/functions/variables in the codes like examplefun() below:
//...defining examplefunc()....//
const int a=0;
if (a>0)
int b=examplefunc();
Upvotes: 3
Views: 465
Reputation: 208456
I don't think the question is correctly stated. While the question literally asks whether the compiler will optimize away a function that is not used, but that is something that only the linker can do.
So what can the compiler do? The compiler can optimize away dead code, so for example in your code above, and because a
is known to be 0
, the compiler can remove the if
statement altogether. For most uses, that is good enough (whether a function makes it to the executable or not won't affect performance much, whether a branch is avoided or not will affect the performance of the function --in particular with branch mispredictions).
Additionally, if the compiler optimizes the branch above, there will be one less reference to the exampleFunc
function in the program, and when the linker processes the generated binaries, if there is no reference to a function in the whole program, it can drop the symbol altogether. Note that this can only be done as part of the program linkage, for libraries, even if the function is not called now, a program linked with the library at a later time might use it.
So getting back to the original question, the compiler will optimize away the branch, and the linker might or not remove the function from the binary, but that should not matter as much.
Regarding the other constructs, for struct
and class
, the only thing that makes it to the binary are the member functions, and the same thing applies there: if you are linking the program and none of the functions is used, the linker can drop the symbols.
Upvotes: 3
Reputation: 59623
The compiler does not usually optimize out unused functions unless they are static
and, therefore, only accessible within a specific module. However, the linker might dead strip the function if linking is done at the function level and not the module level.
You can check the assembly output, linker map, or use something like objdump
to check if the function was included in the linked binary.
Upvotes: 4