简体   繁体   English

在标头中声明和初始化静态int

[英]Declaring and initializing a static int in a header

If I have the following in a header file: 如果我在头文件中有以下内容:

Foo.h foo.h中

Foo
{
public:
  static const int BAR = 1234;
  ...
};

Do I also need to define the variable in the .cpp, eg: 我是否还需要在.cpp中定义变量,例如:

Foo.cpp Foo.cpp中

const int Foo::BAR;

We have an issue where initializing a static in a header seems to work on MS compilers but with gcc on the Mac it seems to give linker errors. 我们有一个问题,在标头中初始化静态似乎可以在MS编译器上运行,但是在Mac上使用gcc时,似乎会出现链接器错误。

You need both the declaration and the definition, just as you've written them. 就像编写它们一样,您需要声明和定义。

Since it is an integer, you can initialise it in the declaration as you've done, and the compiler should treat it as a compile-time constant when it can. 由于它是整数,因此您可以在声明中对其进行初始化,并且编译器应尽可能将其视为编译时常量。 But it still needs one (and only one) definition in a source file, or you'll get link errors when it can't be treated as a constant. 但是它仍然需要源文件中的一个(并且只有一个)定义,否则当您不能将其视为常量时,您将获得链接错误。

Apparently, Microsoft decided that the standard behaviour was too confusing, and "extended" the language to treat a declaration with an initialiser as a definition; 显然,Microsoft认为标准行为过于混乱,因此“扩展”了该语言,无法将声明以初始化程序作为定义。 see this issue . 看到这个问题 The result is that you get link errors (multiply defined symbols) if you also define the symbol correctly. 结果是,如果您还正确定义符号,则会出现链接错误(多重定义的符号)。 You can get the standard behaviour by disabling language extensions ( /Za ). 您可以通过禁用语言扩展( /Za )获得标准行为。

The first fragment works for some environments but the definition really is required by some compilers and of course if you take the address of your constant. 第一个片段适用于某些环境,但是某些编译器确实需要定义,当然,如果使用常量地址,则当然需要。

If you don't like to have to touch header and body to introduce the constant, there still is the old enum-trick: 如果您不想触摸标头和正文以引入常量,那么仍然有旧的枚举技巧:

class A
{
   public:
       enum { someconstant=1234 };
};

makes someconstant available as a compile time constant without the need of a definition in the body. 使某些常量可用作编译时常量,而无需在体内进行定义。

Declarations should be done in the headers and initializations should be done on the .cpp 声明应在标题中完成,而初始化应在.cpp上完成

There's an interesting article about static member variables here . 有一个关于静态成员变量一篇有趣的文章在这里

The header file 头文件

Foo
{
public:
  static const int BAR;
  ...
};

The code file 代码文件

const int Foo::BAR = 1234;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM