同时使用#ifndef,.h文件多次添加 [英] While using #ifndef, .h file being added multiple times
问题描述
我尝试使用以下模式。
#ifndef TRACER_H
#include "Tracer.h"
#endif
这是语句添加到代码中的每个文件,使得tracer.h只添加一次。
This is statement is added to each file in the code such that tracer.h is added only once. Still I am getting an error saying multiple objects.
此外,Tracer.h包含
Also Tracer.h contains
#ifndef TRACER_H
#define TRACER_H
错误;
i尝试pragma一次:
Here is the error; i tried pragma once as well:
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"
推荐答案
看起来很简单:
// some_header.h
#ifndef SOME_HEADER_INCLUDED_H
#define SOME_HEADER_INCLUDED_H
// ...
#endif
其次,这些保护只保护多个包含每个转换单元。如果你有 main.cpp
code> foo.cpp ,每个都包含:
Secondly, these guards only protect from multiple includes per-translation-unit. If you have main.cpp
and foo.cpp
, and each contains:
#include "some_header.h"
#include "some_header.h" // again
// ...
包含守卫之间的内容只会包含一次每个单位,但会定义两次,每个单位一个。
The contents in-between the include guards will be included only once per-unit, but will be defined twice, one in each unit.
当链接时间到来时,你会得到多重定义的错误。您需要在一个源文件中定义这些静态变量,并且只在标题中声明。
When link time comes, you'll get multiple-definition errors. You need to have those static variables defined in one source file, and only declare it in the header.
这篇关于同时使用#ifndef,.h文件多次添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!