如何在C ++中声明一个全局变量 [英] How to declare a global variable in C++
问题描述
我知道一个人不应该使用全局变量,但我需要他们。我已经读过任何在函数之外声明的变量是一个全局变量。我这样做,但在另一个* .cpp文件中找不到该变量。所以这不是真正的全球。不是这样的,必须创建一个头文件GlobalVariabels.h并将该文件包含到使用它的任何其他* cpp文件中?
I know one should not use global variables but I have a need for them. I have read that any variable declared outside a function is a global variable. I have done so, but in another *.cpp File that variable could not be found. So it was not realy global. Isn't it so that one has to create a header file GlobalVariabels.h and include that file to any other *cpp file that uses it?
推荐答案
我读过任何在函数之外声明的变量是一个全局变量。我这样做,但在另一个* .cpp文件中找不到该变量。
I have read that any variable declared outside a function is a global variable. I have done so, but in another *.cpp File that variable could not be found. So it was not realy global.
根据范围的概念,变量 全局。
According to the concept of scope, your variable is global. However, what you've read/understood is overly-simplified.
您可能忘了在其他翻译单元(TU)中声明变量。下面是一个例子:
Perhaps you forgot to declare the variable in the other translation unit (TU). Here's an example:
int x = 5; // declaration and definition of my global variable
b.cpp
b.cpp
// I want to use `x` here, too.
// But I need b.cpp to know that it exists, first:
extern int x; // declaration (not definition)
void foo() {
cout << x; // OK
}
通常你会放置 extern int包含在 b.cpp 中的头文件中的
,以及最终需要使用 x
。
Typically you'd place extern int x;
in a header file that gets included into b.cpp, and also into any other TU that ends up needing to use x
.
变量可能具有内部链接,这意味着它不会跨翻译单元公开。如果变量被标记为 const
( [C ++ 11:3.5 / 3]
):
Additionally, it's possible that the variable has internal linkage, meaning that it's not exposed across translation units. This will be the case by default if the variable is marked const
([C++11: 3.5/3]
):
const int x = 5; // file-`static` by default, because `const`
b.cpp
b.cpp
extern const int x; // says there's a `x` that we can use somewhere...
void foo() {
cout << x; // ... but actually there isn't. So, linker error.
}
您可以通过应用 extern
到定义:
extern const int x = 5;
这整个malarky大致相当于通过使功能在TU边界之间可见/可用,但在如何处理它有一些差异。
This whole malarky is roughly equivalent to the mess you go through making functions visible/usable across TU boundaries, but with some differences in how you go about it.
这篇关于如何在C ++中声明一个全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!