[英]Include statements outside include guards
I recently started working on a project where I came across this: 我最近开始着手研究一个遇到以下问题的项目:
#include <string.h> // includes before include guards
#include "whatever.h"
#ifndef CLASSNAME_H // header guards
#define CLASSNAME_H
// The code
#endif
My question: Considering all (included) header files were written in that same style: Could this lead to problems (cyclic reference, etc.). 我的问题:考虑所有(包含的)头文件都是以相同的样式编写的:这是否可能导致问题(循环引用等)。 And: Is there any (good) reason to do this?
并且:是否有(充分)理由这样做?
Potentially, having #include
outside the include guards could lead to circular references, etc. If the other files are properly protected, there isn't an issue. 将
#include
包含在include防护之外可能会导致循环引用等。如果其他文件受到了适当的保护,则不会有问题。 If the other files are written like this one, there could be problems. 如果其他文件是这样写的,则可能会出现问题。
No, there isn't a good reason that I know of to write the code with the #include
lines outside the include guards. 不,我不知道有充分的理由要使用包含保护程序之外的
#include
行来编写代码。
The include guards should be around the whole contents of the header; 头文件的所有内容都应包含include防护; I can't think of an exception to this (when header guards are appropriate in the first place — the C header
<assert.h>
is one which does not have header guards for a good reason). 我想不到一个例外(首先应该使用标头保护
<assert.h>
– C标头<assert.h>
是没有理由的没有标头保护<assert.h>
那个)。
As long as you don't have circular includes ( whatever1.h
includes whatever2.h
which includes whatever1.h
) this should not be a problem, as the code itself is still protected against multiple inclusion. 只要您没有循环包含(
whatever1.h
包括whatever2.h
,其中包括whatever1.h
),这就不成问题,因为代码本身仍然可以避免多重包含。
It will however almost certainly impact compile time (how much depends on the project size) for two reasons: 但是,它几乎可以肯定会影响编译时间(多少取决于项目大小),原因有两个:
#includes
of that file (just like #pragma once
). #includes
(就像#pragma once
)。 The structure you are showing prevents that optimization. In any case, I can't think of any benefit such a structure would have. 无论如何,我想不出这种结构会有什么好处。 Maybe it is the result of some strange historical reasons, like some obscure analysis tool that was used on your codebase in pre-standard C++ time.
也许是某些奇怪的历史原因造成的,例如在标准C ++时代在代码库上使用了一些晦涩的分析工具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.