编译此代码示例时
#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;
}
Run Code Online (Sandbox Code Playgroud)
它在编译为C++时有效,但在使用相同的编译器(MingW gcc)时不能用作C语言.我得到一个initializer element is not constantC模式.
显然静态初始化存在差异.是否有理由为C++显然允许这样做而不是C?这是因为否则你将无法拥有带构造函数的全局对象?
C++ 编译器生成一个附加的“Start”函数,其中所有“全局函数调用”在 PC(程序计数器)设置为“main”地址之前执行。
“全局函数调用”是为了初始化全局对象而执行的任何函数调用(包括隐式函数调用,即构造函数)。
C 编译器不会生成这样的“Start”函数,并且一旦操作系统加载可执行文件并运行该进程,PC 就会设置为“main”。