在.cpp中包含guard的功能是什么(不是.h)? [英] What is the function of include guard in .cpp (not in .h)?

查看:183
本文介绍了在.cpp中包含guard的功能是什么(不是.h)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,可能这个问题已经有答案,但我不知道什么关键字搜索(大多数我的搜索结果是关于包括警卫在 .h 只有,但不在 .cpp

Ok, may be this question have answer already but I don't know what keyword to search (most of my searched results are about include guard in .h only, but not in .cpp)

有时我在 cpp 每个# include 行都有一个额外的包含守卫(有时甚至包括 .h )像这样:
SomeClass.cpp

Sometimes I saw in cpp each #include line have a extra include guard (sometimes even the included .h already have the own include guard) like this: SomeClass.cpp

#ifndef__A__
#include A.h
#endif
#ifndef__B__
#include B.h
#endif
#ifndef__C__
#include C.h
#endif

而不是

SomeClass.cpp

SomeClass.cpp

#include A.h
#include B.h
#include C.h

,这包括guard的功能是什么?

, what is the function of this include guard?

推荐答案

cpp文件由John Lakos在他的书大型C ++软件设计中推荐。

The practice of using include guards in .cpp files was recommended by John Lakos in his book Large-Scale C++ Software Design. I don't know whether any one before him had recommended the practice.

假设你有

#ifndef __A__
#define __A__

#include "B.h"
#include "C.h"

// ...
// ...
// ...

#endif

Bh:

#ifndef __B__
#define __B__

// ...
// ...
// ...

#endif

Ch:

#ifndef __C__
#define __C__

// ...
// ...
// ...

#endif

SomeClass.cpp:

SomeClass.cpp:

#ifndef __A__
#include "A.h"
#endif

#ifndef __B__
#include "B.h"
#endif

#ifndef __C__
#include "C.h"
#endif

当SomeClass.cpp编译时,包括Ah的内容。作为包括A.h的内容的副产物,还包括B.h和C.h的内容。此外,预处理程序宏 __ A __ __ B __ __ C __ 被定义。当行

When SomeClass.cpp is compiled, the contents of A.h is included. As a by-product of including the contents of A.h, the contents of B.h and C.h are also included. Also, the pre-processor macros __A__, __B__ and __C__ are defined. When the line

#ifndef __B__

$ b因为 __ B __ 已经定义,所以处理
$ b

,下一行被跳过。

is processed, since __B__ is already defined, the next line is skipped.

If SomeClass.cpp has just:

If SomeClass.cpp had just:

#include "A.h"
#include "B.h"
#include "C.h"

文件必须被打开和处理。

the file B.h has to be opened and processed. The contents of the file will not be included again due to the include guards but the file has to be opened and closed.

通过使用第一个策略,您可以避免成本增加的开和关Bh和Ch对于大型C ++项目,John Lakos断言,成本太高了。因此,建议使用包含守卫甚至在.cpp文件。

By using the first strategy, you avoid the cost of of opening and closing B.h and C.h. For large scale C++ project, John Lakos asserts, the cost is too much. Hence, the recommendation of using include guards even in .cpp files.

这篇关于在.cpp中包含guard的功能是什么(不是.h)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆