考虑以下.我有两个导出的常量如下:
// somefile.h
extern const double cMyConstDouble;
extern const double cMyConstDouble2;
和
// somefile.cpp
const double cMyConstDouble = 3.14;
const double cMyConstDouble2 = 2.5*cMyConstDouble;
现在引用这些常量来定义两个静态(局部可见)常量:
// someotherfile.cpp
#include "somefile.h"
static const double cAnotherDouble = 1.1*cMyConstDouble;
static const double cAnotherDouble2 = 1.1*cMyConstDouble2;
printf("cAnotherDouble = %g, cAnotherDouble2 = %g\n",
cAnotherDouble, cAnotherDouble2);
产生以下输出:
cAnotherDouble = 3.454, cAnotherDouble2 = 0
为什么第二双0?我正在使用.NET 2003 C编译器(13.10.3077).
解决方法:
由于cMyConstDouble声明为extern,因此编译器无法假定其值并且不会为cMyConstDouble2生成编译时初始化.由于cMyConstDouble2未初始化编译时间,因此其相对于cAnotherDouble2的初始化顺序是随机的(未定义).有关更多信息,请参见static initialization fiasco.