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

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

问题描述

static关键字将全局变量的范围限制为该翻译单元。
如果我在.h文件中使用 static int x 并在每个其他文件中都包含该.h文件,它们是否都属于同一个翻译单元?
那么,x到处都不可见吗?
那么static的作用是什么?

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?

此外, static const int x ,其中x是全局变量?
默认情况下,不是所有const全局变量都是静态的吗?
并且const变量的作用域是否仅限于TU,即使它局限于文件中的for循环中?

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?

推荐答案

如果您写

static const int x

放在 .h 文件中,然后每个 #include -s .h 的翻译单元拥有自己的私有变量 x

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

如果您想让每个人都可以看到1个全局变量,则应该编写

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

extern const int x;

const int x = ...;

.cpp 文件之一中。

如果您只想让一个翻译单元可见一个静态const int,则不要在 .h 文件中完全提及它。

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.

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

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