在头中声明和初始化静态int [英] Declaring and initializing a static int in a header

查看:97
本文介绍了在头中声明和初始化静态int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在头文件中有以下内容:

If I have the following in a header file:

Foo.h

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

我还需要在.cpp中定义变量,例如:

Do I also need to define the variable in the .cpp, e.g.:

Foo.cpp

const int Foo::BAR;

我们有一个问题,在头文件中初始化静态似乎在MS编译器上工作,但gcc on Mac似乎给了链接器错误。

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.

推荐答案

你需要声明和定义,就像你写的。

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.

显然,微软决定标准的行为太混乱,扩展语言来用一个初始化器作为定义来处理一个声明;请参阅此问题 。结果是,如果您还正确定义了符号,则会得到链接错误(乘以定义的符号)。您可以通过禁用语言扩展( / Za )获得标准行为。

Apparently, Microsoft decided that the standard behaviour was too confusing, and "extended" the language to treat a declaration with an initialiser as a definition; 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).

这篇关于在头中声明和初始化静态int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆