我正在尝试使用以下模式。
#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.cpp
和 foo.cpp
,并且每个包含:
#include "some_header.h"
#include "some_header.h" // again
// ...
包含守卫之间的内容每个单元只会被包含一次,但会被定义两次,每个单元一个。
当链接时间到来时,您将遇到多重定义错误。您需要在一个源文件中定义这些静态变量,并且只在 header 中声明它。
关于c++ - 使用#ifndef 时,.h 文件被多次添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2663702/