Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the compiler know to call function once per static variable?

Tags:

c++

static

E.g

 foo1() {
     static const char* str = foo2();

 }

 const char * foo2 () {

     ...
 }

How does the compiler makes sure it calls foo2 just once.

like image 927
kal Avatar asked Feb 28 '23 01:02

kal


1 Answers

foo2 is called at the initialisation of your program, just before main().

Edit: this is wrong! I assumed this as this is how normally static initialisation works. But in this case, they are called once at the start of the function.

It must work with some kind of static boolean. Yep. At least in gcc, this:

int test2()
{
    static int bla = test();
}

Compiles to:

 8048616: b8 30 a0 04 08        mov    $0x804a030,%eax
 804861b: 0f b6 00              movzbl (%eax),%eax
 804861e: 84 c0                 test   %al,%al
 8048620: 75 52                 jne    8048674 <_Z5test2v+0x67>
 ...
 804863c: e8 b3 ff ff ff        call   80485f4 <_Z4testv>
 ...
 8048674: 83 c4 1c              add    $0x1c,%esp
 8048677: 5b                    pop    %ebx
 8048678: 5e                    pop    %esi
 8048679: 5f                    pop    %edi
 804867a: 5d                    pop    %ebp
 804867b: c3                    ret    

So it uses a hidden, function specific boolean (at $0x804a030) + some magic to protect against exceptions and multiple threads calling it at once.

like image 95
wump Avatar answered Mar 08 '23 22:03

wump