When compiling this code sample
#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 an initializer element is not constant
in C mode.
So apparently there are differences regarding static intialization. Is there a reason why this is apparently allowed for C++ but not for C? Is this because otherwise you wouldn't be able to have global objects with constructor functions?
C++ compiler generates an additional 'Start' function, where all "global function calls" are executed before the PC (program counter) is set to the address of 'main'.
A "global function call" is any function-call which is performed in order to initialize a global object (including implicit function calls, i.e., constructors).
C compiler does not generate such 'Start' function, and the PC is set to 'main' as soon as the OS loads the executable and runs the process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With