error LNK2005: 已定义两次包含头文件

error LNK2005: already defined on including a header file twice

我需要在 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,说明该参数已在另一个对象中定义。

参考同样错误的其他问题,我才知道here

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

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

您可能忘记添加 include guard:

Header.h

#ifndef HEADER_H
#define HEADER_H

namespace something {
}

#endif

另一种选择是在头文件的开头使用 #pragma once

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

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

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

global.hpp

#pragma once

namespace global {
   extern int variable;
}

global.cpp

namespace global {
   int variable = 0;
}

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