跨文件的C ++引用变量 [英] C++ reference variable across files
本文介绍了跨文件的C ++引用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个项目,我需要引用在另一个CPP文件中声明的变量,是否可能?
I have a project where I need to reference a variable declared in one CPP file in another, is that possible?
如果是,
If so, how?
推荐答案
如果你声明它是全局的(顶层,高于任何函数定义)并使用extern;在其他文件中,以使编译器知道。
It is possible, if you declare it as global (top-level, above any function definition) and use "extern ;" in other files to make it known to the compiler.
// Main.cpp
#include <...>
int myNum;
int main(int argc, char** argv)
{
// MAGIC BE HERE
return 0;
}
和
// Second.cpp
#include <...>
extern int myNum;
int f()
{
return myNum * 2;
}
extern
编译器在另一个文件中分配变量时再次分配内存。
extern
prevents the compiler from allocating memory again when a variable was allocated in another file.
这篇关于跨文件的C ++引用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文