从另一个文件访问 C++ 中的外部变量
我在其中一个 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.
推荐答案
抱歉,我忽略了对建议使用头文件以外的任何其他内容的答案的请求.这就是标题的用途,当您正确使用它们时...仔细阅读:
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.
相关文章