c++ - Visual Studio 2010 多个 cpp 文件

标签 c++ visual-studio-2010 file

我是 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/

相关文章:

c++ - 使用VS2010在Windows Server 2008平台远程调试C++;缺少 MSVCP100D.dll

c++ - Windows 中以毫秒为单位的时间戳

c++ - typedef 一个 vector 和固定大小的 boost::numeric::ublas::vector

visual-studio-2010 - 使用 InstallShield LE 从默认设置自定义 setup.exe 图标

c# - 编码UI : Why is searching for a cell so slow?

perl - 使用 WWW::Mechanize 自动搜索

file - 如何使用powershell检查文件夹中是否存在特定的文件扩展名?

javascript - 如何将FileList数组添加到<input type ='file'>控件中?

c++ - 自动参数如何在内部工作?

c++ - 浮点运算