c++ - 错误 LNK2005 : already defined on including a header file twice

标签 c++ visual-studio-2013 namespaces include lnk2005

我需要在 Visual Studio 项目的多个 cpp 文件中编辑和访问一些变量。所以我创建了一个头文件,它的命名空间包含我需要的所有变量,如下所示:

namespace windowdimension{
    TCHAR openwindows[20][180];
    int winnum = 0;
    int windowleft = 0;
    int windowright = 1360;
    INT windowtop = 0;
    INT windowbottom = 768;
    LONG leftarray[20];
    LONG rightarray[20];
    LONG toparray[20];
    LONG bottomarray[20];

}

但是,如果我在两个源文件中#include 这个头文件,我会得到这个链接器错误 2005,说参数已经在另一个 obj 中定义了。

引用同样错误的其他问题,我知道了here那个

a function definition can only appear once. Every .cpp file that #includes your .h file will generate yet another copy of the function.

但这也适用于命名空间变量吗? 如果是这样,我们如何确保跨多个源文件访问特定变量?

最佳答案

永远不要在头文件中定义全局变量。

为了能够共享,您需要在头文件中声明它们(使用 extern 关键字),并且在 .cpp 文件中只定义一次。

当然,永远不要忘记在每个头文件中包含保护(#pragma once 是非常便携的解决方案):

全局.hpp

#pragma once

namespace global {
   extern int variable;
}

全局.cpp

namespace global {
   int variable = 0;
}

无论如何,使用全局变量是一种非常糟糕的做法。

关于c++ - 错误 LNK2005 : already defined on including a header file twice,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33015597/

相关文章:

ruby-on-rails - 添加 Admin 命名空间时的路由错误

c++ - 删除 using namespace std 会导致程序得到错误的结果

debugging - Visual Studio 2013 调试键盘快捷键不起作用

c++ - 模板化 namespace 和 typedef 是非法的——解决方法?

visual-studio-2013 - VS 2013 Update 3 - 不支持 TypeScript

javascript - ReSharper 对于 JavaScript 文件非常慢

c# - 将类移动到文件夹后更新所有类文件中的命名空间名称

c++ - 初始化时返回一个指针? C++

c++ - 类模板中的多个可选成员,无需开销

c++ - 非托管 C++ tlh 文件未更新?