The only code path that calls the function comes from main
GCC can't know that unless you tell it so with -fwhole-program
or maybe -flto
(link-time optimization). Otherwise it has to assume that some static constructor in another compilation unit could call it. (Including possibly in a shared library, but another .cpp
that you link with could do it.) e.g.
// another .cpp
typedef struct { bool some_var; } model_t;
void bla(const model_t *m); // declare the things from the other .cpp
int foo() {
model_t model = {false};
bla(&model);
return 1;
}
int some_global = foo(); // C++ only: non-constant static initializer.
Example on Godbolt with these lines in the same compilation unit as main, showing that it outputs both Some var is false!
and then Some var is true!
, without having changed the code for main
.
ISO C doesn't have easy ways to get init code executed, but GNU C (and GCC specifically) have ways to get code run at startup, not called by main
. This works even for shared libraries.
With -fwhole-program
, the appropriate optimization would be simply not emitting a definition for it at all, as it's already inlined into the call-site in main
. Like with inline
(In C++, a promise that any other caller in another compilation unit can see its own definition of the function) or static
(private to this compilation unit).
Inside main
, it has optimized away the branch after constant propagation. If you ran the program, no branch would actually execute; nothing calls the stand-alone definition of the function.
The stand-alone definition of the function doesn't know that the only possible value for m
is &model
. If you put that inside the function, then it could optimize like you're expecting.
Only -fPIC
would force the compiler to consider the possibility of symbol-interposition so the definition of const model_t model
isn't the one that is in effect after (dynamic) linking. But you're compiling code for an executable not a library. (You can disable symbol-interposition for a global variable by giving it "hidden" visibility, __attribute__((visibility("hidden")))
, or use -fvisibility=hidden
to make that the default).
bla
static
, compiler may optimize it.bla
call inmain
and optimized theelse
branch away there. It just has to emit the function in case another translation unit uses it. (Compiler explorer is showing you the output after compilation before linking.)bla
was inlined? The image in the question shows the assembly output from the compiler. In the emittedmain
function there is no call tobla
, just a call toputs
with its argument loaded unconditionally from.LC0
which is the string in the first branch of theif
. So the branching was optimized away.