foo2 is called when you initialize your program immediately before main () .
Edit: this is wrong ! I assumed this since static initialization usually works. But in this case they are called once at the beginning of the function.
It should work with some kind of static boolean. Yeah. At least in gcc, this is:
int test2() { static int bla = test(); }
Compiles:
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
Thus, it uses a hidden, function-specific logical (in $ 0x804a030) + some magic to protect against exceptions and several threads that cause it at once.
source share