我是 Visual Studio 的新手,目前正在处理一个项目,我想在其中使用多个 .cpp 文件。基本上我想在 function.cpp 中的 main.cpp 之外创建一个函数,并且该函数应该能够更改全局变量。然后我会在 main.cpp 中使用该函数。
我尝试制作一个名为 globals.h 的 header 并将静态变量放入其中。我在 main 和 function.cpp 中都包含了 globals.h 并编译了它,但是每当我在 main 中调用该函数时,它什么都不做。 当我尝试在 main.cpp 中包含 function.cpp 时,我在编译时遇到多重定义错误。
我做错了什么?提前致谢!
最佳答案
不要在头文件中使用static
变量。由于 header “合并”在编译单元中,因此 header 中声明为 static
的所有变量仅在编译单元内起作用。您将无法在您的 cpp 文件中使用相同的全局变量。
你的结构应该是这样的:
globals.h
------
extern int my_global_integer;
main.cpp
------
#include "globals.h"
// here use my_global_integer;
function.cpp
------
#include "globals.h"
// global variables have to be declared in exactly one compilation unit.
// otherwise the linker will complain that the variable is defined twice.
int my_global_integer = 0;
关于c++ - Visual Studio 2010 多个 cpp 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7994048/