为什么一些引用某些导出的const变量的const变量的值为0?

ral*_*nja 2 c++ double initialization const extern

考虑以下.我有两个导出的常量如下:

// somefile.h
extern const double cMyConstDouble;
extern const double cMyConstDouble2;
Run Code Online (Sandbox Code Playgroud)

// somefile.cpp
const double cMyConstDouble = 3.14;
const double cMyConstDouble2 = 2.5*cMyConstDouble;
Run Code Online (Sandbox Code Playgroud)

现在引用这些常量来定义两个静态(局部可见)常量:

// 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);
Run Code Online (Sandbox Code Playgroud)

产生以下输出:

cAnotherDouble = 3.454, cAnotherDouble2 = 0
Run Code Online (Sandbox Code Playgroud)

为什么第二双0?我正在使用.NET 2003 C++编译器(13.10.3077).

小智 9

我不打算在这里讨论extern的问题,但是为什么你不把consts放在适当的头文件中而忘记使用extern"导出"它们?这就是C++中应该使用的consts,以及为什么它们具有内部链接.

换一种说法:

// someheader.h
const double cMyConstDouble = 3.14;
const double cMyConstDouble2 = 2.5*cMyConstDouble;
Run Code Online (Sandbox Code Playgroud)

和#include该文件,无论你需要它们.

  • 然后你的代码库的架构出了问题.我在过去十年中编写和审阅的所有C++代码都使用了我的方式,完全没有问题. (2认同)

Sum*_*uma 8

由于cMyConstDouble声明为extern,因此编译器无法假定其值,也不会为cMyConstDouble2生成编译时初始化.由于cMyConstDouble2未初始化编译时间,因此其相对于cAnotherDouble2的初始化顺序是随机的(未定义).有关更多信息,请参阅静态初始化失败.