c++ - 使用#ifndef 时,.h 文件被多次添加

标签 c++ c-preprocessor

我正在尝试使用以下模式。

#ifndef TRACER_H
#include "Tracer.h"
#endif

此语句被添加到代码中的每个文件,这样 tracer.h 只添加一次。 我仍然收到多个对象的错误消息。

Tracer.h 还包含

#ifndef TRACER_H
#define TRACER_H

这是错误; 我也试过 pragma 一次:

1>Generating Code...
1>Linking...
1>LINK : \\stu05-fsrv.ad.syr.edu\akbhat$\Visual Studio 2008\Projects\Project3\Debug\Project3.exe not found or not built by the last incremental link; performing full link
1>SemiExpression.obj : error LNK2005: "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class tracer &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAVtracer@@@Z) already defined in main.obj
1>SemiExpression.obj : error LNK2005: "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > tracer::log" (?log@tracer@@0V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A) already defined in main.obj
1>Tokenizer.obj : error LNK2005: "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class tracer &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAVtracer@@@Z) already defined in main.obj
1>Tokenizer.obj : error LNK2005: "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > tracer::log" (?log@tracer@@0V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A) already defined in main.obj
1>\\stu05-fsrv.ad.syr.edu\akbhat$\Visual Studio 2008\Projects\Project3\Debug\Project3.exe : fatal error LNK1169: one or more multiply defined symbols found
1>Build log was saved at "file://\\stu05-fsrv.ad.syr.edu\akbhat$\Visual Studio 2008\Projects\Project3\Project3\Debug\BuildLog.htm"

最佳答案

首先,header guards进入文件内部。它使它变得容易得多:

// some_header.h
#ifndef SOME_HEADER_INCLUDED_H
#define SOME_HEADER_INCLUDED_H

// ...

#endif

其次,这些守卫只保护免受多重包含 per-translation-unit。如果您有 main.cppfoo.cpp,并且每个包含:

#include "some_header.h"
#include "some_header.h" // again

// ...

包含守卫之间的内容每个单元只会被包含一次,但会被定义两次,每个单元一个。

当链接时间到来时,您将遇到多重定义错误。您需要在一个源文件中定义这些静态变量,并且只在 header 中声明它。

关于c++ - 使用#ifndef 时,.h 文件被多次添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2663702/

相关文章:

c++ - 使用给定的第一个和最后一个迭代器迭代范围

c++ - C++ 中的一个特殊的 Person 类

gcc - C 预处理器添加了自己的注释

C 宏 : Conditional code based on parameter value?

c++ - C++11 标准中的哪个子句允许我在下面的 `A` 中删除 `return` 语句中的 `A::operator-()`?

c++ - 所有 OpenCV 函数都会抛出异常吗?

c++ - 在树中搜索值

c - MACROS - 如何实现除法然后舍入

c++ - 在 c++ Eclipse CDT 中使用不同的值构建

c - 与 C 函数定义一起使用的预处理器宏定义