从另一个文件访问C ++中的extern变量 [英] Access extern variable in C++ from another file
问题描述
我在一个cpp文件中有一个全局变量,在其中给它分配一个值。现在,为了能够在另一个cpp文件中使用它,我将其声明为 extern
,并且此文件具有使用它的多个功能,因此我在全局范围内进行操作。现在可以在一个函数中访问此变量的值,而不能在另一个函数中访问。除了在头文件中使用它以外,其他任何建议都是很好的,因为我浪费了4天时间。
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.
推荐答案
对不起,我m忽略了对答案的要求,该答案建议使用头文件以外的任何内容。这是标题的用途,当您正确使用它们时...仔细阅读:
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
#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
// 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:
- 将每个源(.cpp)文件编译为目标文件;
- 链接所有目标文件以创建目标文件可执行文件/库/等等。
使用我上面给出的语法,您应该既没有编译错误也没有链接错误。
Using the syntax I have given above, you should have neither compile nor link errors.
这篇关于从另一个文件访问C ++中的extern变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!