头文件中的变量声明 - 静态与否?
在重构一些 #defines
时,我在 C++ 头文件中遇到了类似于以下内容的声明:
When refactoring away some #defines
I came across declarations similar to the following in a C++ header file:
static const unsigned int VAL = 42;
const unsigned int ANOTHER_VAL = 37;
问题是,静态会产生什么不同(如果有)?请注意,由于经典的 #ifndef HEADER
#define HEADER
#endif
技巧(如果这很重要),因此不可能包含多个标头.
The question is, what difference, if any, will the static make? Note that multiple inclusion of the headers isn't possible due to the classic #ifndef HEADER
#define HEADER
#endif
trick (if that matters).
静态是否意味着只创建 VAL
的一个副本,以防头文件包含在多个源文件中?
Does the static mean only one copy of VAL
is created, in case the header is included by more than one source file?
推荐答案
static
意味着将为包含它的每个源文件创建一个 VAL
副本但这也意味着多个包含不会导致 VAL
的多个定义在链接时发生冲突.在 C 中,如果没有 static
,您需要确保只有一个源文件定义了 VAL
,而其他源文件声明了它 extern
.通常可以通过在源文件中定义它(可能使用初始值设定项)并将 extern
声明放在头文件中来实现.
The static
means that there will be one copy of VAL
created for each source file it is included in. But it also means that multiple inclusions will not result in multiple definitions of VAL
that will collide at link time. In C, without the static
you would need to ensure that only one source file defined VAL
while the other source files declared it extern
. Usually one would do this by defining it (possibly with an initializer) in a source file and put the extern
declaration in a header file.
static
全局级别的变量仅在它们自己的源文件中可见,无论它们是通过包含还是在主文件中.
static
variables at global level are only visible in their own source file whether they got there via an include or were in the main file.
编者注:在 C++ 中,声明中既没有 static
也没有 extern
关键字的 const
对象是隐式static
.
Editor's note: In C++, const
objects with neither the static
nor extern
keywords in their declaration are implicitly static
.
相关文章