C++ 多个文件中的全局变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3627941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Global Variable within Multiple Files
提问by kaykun
I have two source files that need to access a common variable. What is the best way to do this? e.g.:
我有两个需要访问公共变量的源文件。做这个的最好方式是什么?例如:
source1.cpp:
源1.cpp:
int global;
int function();
int main()
{
global=42;
function();
return 0;
}
source2.cpp:
源2.cpp:
int function()
{
if(global==42)
return 42;
return 0;
}
Should the declaration of the variable global be static, extern, or should it be in a header file included by both files, etc?
变量 global 的声明应该是静态的、外部的,还是应该在两个文件都包含的头文件中等等?
回答by e.James
The global variable should be declared extern
in a header file included by both source files, and then defined in only one of those source files:
全局变量应extern
在两个源文件都包含的头文件中声明,然后仅在其中一个源文件中定义:
common.h
通用文件
extern int global;
source1.cpp
源1.cpp
#include "common.h"
int global;
int function();
int main()
{
global=42;
function();
return 0;
}
source2.cpp
源2.cpp
#include "common.h"
int function()
{
if(global==42)
return 42;
return 0;
}
回答by harper
You add a "header file", that describes the interface to module source1.cpp:
您添加一个“头文件”,它描述了模块 source1.cpp 的接口:
source1.h
源文件1.h
#ifndef SOURCE1_H_
#define SOURCE1_H_
extern int global;
#endif
source2.h
源文件2.h
#ifndef SOURCE2_H_
#define SOURCE2_H_
int function();
#endif
and add an #include statement in each file, that uses this variable, and (important) that defines the variable.
并在每个文件中添加一个 #include 语句,该语句使用此变量,并且(重要)定义该变量。
source1.cpp
源1.cpp
#include "source1.h"
#include "source2.h"
int global;
int main()
{
global=42;
function();
return 0;
}
source2.cpp
源2.cpp
#include "source1.h"
#include "source2.h"
int function()
{
if(global==42)
return 42;
return 0;
}
While it is not necessary, I suggest the name source1.h for the file to show that it describes the public interface to the module source1.cpp. In the same way source2.h describes what is public available in source2.cpp.
虽然不是必需的,但我建议将文件命名为 source1.h,以表明它描述了模块 source1.cpp 的公共接口。以同样的方式,source2.h 描述了 source2.cpp 中公共可用的内容。
回答by Patrick
In one file you declare it as in source1.cpp, in the second you declare it as
在一个文件中,您将其声明为 source1.cpp,在第二个文件中,您将其声明为
extern int global;
Of course you really don't want to be doing this and should probably post a question about what you are trying to achieve so people here can give you other ways of achieving it.
当然,您真的不想这样做,并且可能应该发布有关您要实现的目标的问题,以便这里的人们可以为您提供其他实现方式。