从另一个文件访问 C++ 中的外部变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12290451/
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
Access extern variable in C++ from another file
提问by Venushree Patel
I have a global variable in one of the cpp files, where I am assigning a value to it. Now in order to be able to use it in another cpp file, I am declaring it as extern
and this file has multiple functions that use it so I am doing this globally. Now the value of this variable can be accessed in one of the functions and not in the other one. Any suggestions except using it in a header file would be good because I wasted 4 days playing with that.
我在其中一个 cpp 文件中有一个全局变量,我正在为其分配一个值。现在为了能够在另一个 cpp 文件中使用它,我将它声明为extern
并且这个文件有多个使用它的函数,所以我在全局执行此操作。现在可以在其中一个函数中访问此变量的值,而不能在另一个函数中访问。除了在头文件中使用它之外的任何建议都会很好,因为我浪费了 4 天的时间。
回答by paddy
Sorry, I'm ignoring the request for answers suggesting anything other than the use of header files. This is what headers are for, when you use them correctly... Read carefully:
抱歉,我忽略了对建议使用头文件以外的任何内容的答案的请求。这就是标题的用途,当您正确使用它们时...仔细阅读:
global.h
全局文件
#ifndef MY_GLOBALS_H
#define MY_GLOBALS_H
// This is a declaration of your variable, which tells the linker this value
// is found elsewhere. Anyone who wishes to use it must include global.h,
// either directly or indirectly.
extern int myglobalint;
#endif
global.cpp
全局.cpp
#include "global.h"
// This is the definition of your variable. It can only happen in one place.
// You must include global.h so that the compiler matches it to the correct
// one, and doesn't implicitly convert it to static.
int myglobalint = 0;
user.cpp
用户.cpp
// Anyone who uses the global value must include the appropriate header.
#include "global.h"
void SomeFunction()
{
// Now you can access the variable.
int temp = myglobalint;
}
Now, when you compile and link your project, you must:
现在,当您编译和链接您的项目时,您必须:
- Compile each source (.cpp) file into an object file;
- Link all object files to create your executable / library / whatever.
- 将每个源(.cpp)文件编译成目标文件;
- 链接所有目标文件以创建您的可执行文件/库/任何内容。
Using the syntax I have given above, you should have neither compile nor link errors.
使用我上面给出的语法,您应该既没有编译错误也没有链接错误。