If I compile this code with GCC or Clang and enable -O2
optimizations, I still get some global object initialization. Is it even possible for any code to reach these variables?
#include <string>
static const std::string s = "";
int main() { return 0; }
Compiler output:
main:
xor eax, eax
ret
_GLOBAL__sub_I_main:
mov edx, OFFSET FLAT:__dso_handle
mov esi, OFFSET FLAT:s
mov edi, OFFSET FLAT:_ZNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEED1Ev
mov QWORD PTR s[rip], OFFSET FLAT:s+16
mov QWORD PTR s[rip+8], 0
mov BYTE PTR s[rip+16], 0
jmp __cxa_atexit
Specifically, I was not expecting the _GLOBAL__sub_I_main:
section.
Edit: Even with a simple custom defined type, the compiler still generates some code.
class Aloha
{
public:
Aloha () : i(1) {}
~Aloha() = default;
private:
int i;
};
static const Aloha a;
int main() { return 0; }
Compiler output:
main:
xor eax, eax
ret
_GLOBAL__sub_I_main:
ret
std::string
allows Small/Short string optimization. This normally means that inside the string is a union of achar[]
and the member of string object. That could make the internals opaque to the optimizer so it might still initialize as there could be observable behavior that it doesn't want to accidently remove. – Limpidret
instruction – Borerconst
andstatic
should be redundant here.const
already impliesstatic
in this case. – Soulestd::string
andAloha
have constructors with side effects (initializing members), so the compiler is less likely to optimize them away. – Jacobinismret
corresponds to "all global variables in main.c have been initialized". I don't know why more code is generated for the unused std::string. – Durraconst
global variables viaextern
and it works fine. Something must have changed in a newer version of the standard. – Jacobinismextern
declaration in header included in both modules, it would affect the definition ... a little trick. – Spectrochemistry-std=c++20
the result is the same. Can you give me concrete example with fundamental type, I think I didn't get the full picture ? – Borerconst int&& i = 3;
andstatic const int&& i = 3;
. Andstatic const
was completely optimized out. Maybe I am missing a point but it seems in this caseconst
doesn't completely implystatic
. Also if it is interesting, I may add theconst int&& i = 3;
case to the question as well? – Borerconst
is not top-level in the reference, so what I said doesn't apply to it. – Soule