The difference between static initialization of C and C ++

When compiling this sample code

#include <stdio.h> #include <stdlib.h> int myfunc() { printf("Constructor\n"); return 1; } static const int dummy = myfunc(); int main() { printf("main\n"); return 0; } 

it works when compiled as C ++, but not as C using the same compiler (MingW gcc). I get initializer element is not constant in C mode.

Therefore, apparently, there are differences regarding static initialization. Is there a reason why this is apparently allowed for C ++, but not for C? Is it because otherwise you cannot have global objects with constructor functions?

+6
source share
1 answer

The C ++ compiler generates an additional "Start" function, where all "global function calls" are executed before the PC (program counter) is set to the address "main".

A "global function call" is any function call that is performed to initialize a global object (including calls to implicit functions, that is, constructors).

Compiler

C does not generate such a β€œstart” function, and the PC is installed on β€œmain” as soon as the OS loads the executable file and starts the process.

+2
source

All Articles