Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does GCC keep empty functions?

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?

like image 501
Ákos Kovács Avatar asked Apr 06 '12 22:04

Ákos Kovács


2 Answers

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.

like image 145
Jonathan Leffler Avatar answered Oct 08 '22 02:10

Jonathan Leffler


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).

like image 35
Jens Gustedt Avatar answered Oct 08 '22 02:10

Jens Gustedt