In most cases if I want to create an optional feature in C, I simply create two functions like this:
#ifdef OPTIONAL_SOMETHING
void do_something(int n, const char *s)
{
while (n--) {
printf("%s", s);
}
/* ...You might get the point, really do something... */
}
#else
void do_something(int n, const char *s)
{
/* Empty body */
}
#endif
So if the symbol is undefined — when the feature is disabled — an empty function is compiled into the executable.
Delving into the assembly listing, it seems that GCC compiles and calls the empty functions when the optimizations are disabled. If the optimizations are enabled, also with -O2
and -O3
, it compiles only the necessary stack handling code, but it optimizes out the call instructions. All in all it keeps the function.
About the same applies for the non-empty, but unused methods.
It should simply throw out the whole thing, but it does not. Why it is the default behavior? And just for curiosity: How I can eliminate this?
Since the function has external linkage (is not static
), the compiler cannot eliminate it because another object file might reference it. If the function is static
, it will be eliminated completely.
If you want the compiler to eventually inline the function you got to tell him. Declare your function inline
, this allows the compiler not to emit the function if it sees fit.
Now this may lead to an "undefined symbol" error when you compile with -O0 or so. Put an "instantiation" like
void do_something(int n, const char *s);
in just one compilation unit (.c file).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With