简体   繁体   English

包含声明之外的包含防护

[英]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: 但是,它几乎可以肯定会影响编译时间(多少取决于项目大小),原因有两个:

  1. Modern compilers usually detect "classical" include guards and just ignore any further #includes of that file (just like #pragma once ). 现代编译器通常会检测“经典”包含保护,而忽略该文件的其他任何#includes (就像#pragma once )。 The structure you are showing prevents that optimization. 您显示的结构阻止了这种优化。
  2. Each compilation unit becomes much larger as each file will be included much more often - right before the preprocessor then deletes all the inactive blocks again. 每个编译单元变得越来越大,因为每个文件将被包含得越来越频繁-在预处理器随后再次删除所有不活动块之前。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM