C ++ - 可以在.h文件中声明静态全局变量? [英] C++ - Okay to declare static global variable in .h file?

查看:700
本文介绍了C ++ - 可以在.h文件中声明静态全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

static关键字将全局变量的作用域限制为该翻译单元。
如果在.h文件中使用 static int x ,并且每个其他文件都包含.h文件,那么它们是否都属于同一个翻译单元?
那么,不会在任何地方都可见?
现在静态的作用是什么?



此外,是否有任何使用 static const int x ,其中x是全局变量?
默认情况下,并不是所有的const全局变量都是静态的吗?
是一个const变量的范围限于TU,即使它局限在文件中的for循环中。

解决方案

如果你写

  static const int x 

- 的每个翻译单元都会显示

有自己的私有变量 x



如果你想有一个全局变量对所有人可见, / p>

  extern const int x;在 .h 文件和


中的



<

  const int x = ...; 

.cpp 文件之一。
$ b

如果你想让一个静态const int只对一个翻译单元可见 - 不要在 .h 文件中提及它。


static keyword keeps the scope of a global variable limited to that translation unit. If I use static int x in a .h file and include that .h file every other file, won't they all belong to the same translation unit? Then, won't x be visible everywhere? So what is the role of static now?

Also, is there any use of static const int x ,where x is a global variable? Aren't all const global variables static by default? And is a const variable's scope limited to the TU even if it confined in a for loop in the file?

解决方案

If you write

static const int x

in an .h file then every translation unit that #include-s this .h will have its own private variable x.

If you want to have 1 global variable visible to everyone you should write

extern const int x;

in the .h file and

const int x = ...;

in one of the .cpp files.

If you want to have a static const int visible to just one translation unit - don't mention it in the .h files at all.

这篇关于C ++ - 可以在.h文件中声明静态全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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