Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between C and C++ static initialization [duplicate]

Tags:

c++

c

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?

like image 597
Devolus Avatar asked Jan 11 '14 10:01

Devolus


1 Answers

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.

like image 150
barak manos Avatar answered Oct 12 '22 21:10

barak manos