为什么在2个.CPP文件中包含此头文件(带头文件保护)会导致命名冲突?

时间:2017-01-07 00:03:02

标签: c++ linker

example.h文件:

#ifndef EXAMPLE_H
#define EXAMPLE_H

#include "stdafx.h"
#include <Windows.h>


namespace Test
{
    DWORD foo;
}

#endif

Example.cpp:

#include "stdafx.h"
#include "Example.h"

Example2.cpp:

 #include "stdafx.h"
 #include "Example.h"

Main.cpp的:

#include "stdafx.h"

int main()
{
    return 0;
}

这会导致链接器错误:

error LNK1169: one or more multiply defined symbols found   
error LNK2005: "unsigned long Test::foo" (?foo@Test@@3KA) already defined in Example.obj

此代码将编译,如果&#34; Example.h&#34;未包含在&#34; Example2.cpp&#34;中。根据我的理解,Example.h将仅包含在此示例中一次。如果是这样,为什么foo会发生命名冲突?

1 个答案:

答案 0 :(得分:4)

标头保护仅防止多个包含在同一translation unit(源文件)中。它不能防止不同的翻译单元中的多重包含。

因此,您在两个源文件中定义变量Test::foo

一种解决方案是将头文件中的变量声明标记为extern,并且在单个源文件中基本上将头文件中的声明复制为定义(不包含extern关键字)。 / p>

请注意,这仅适用于变量,而不适用于类或函数或类似函数。

相关问题