在C ++中使用双重包含保护 [英] The use of double include guards in C++

查看:92
本文介绍了在C ++中使用双重包含保护的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我最近在我的工作地点进行了讨论,在此我质疑使用 double 包含卫队对单个卫队的保护.我所说的双重警卫如下:

So I recently had a discussion where I work, in which I was questioning the use of a double include guard over a single guard. What I mean by double guard is as follows:

头文件"header_a.hpp":

#ifndef __HEADER_A_HPP__
#define __HEADER_A_HPP__
...
...
#endif

在头文件或源文件中的任何位置包含头文件时:

When including the header file anywhere, either in a header or source file:

#ifndef __HEADER_A_HPP__
#include "header_a.hpp"
#endif

现在,我知道在头文件中使用防护是为了防止多次包含已定义的头文件,这是常见且有据可查的.如果已经定义了宏,则编译器会将整个头文件视为空白",并防止重复包含.很简单.

Now I understand that the use of the guard in header files is to prevent multiple inclusion of an already defined header file, it's common and well documented. If the macro is already defined, the entire header file is seen as 'blank' by the compiler and the double inclusion is prevented. Simple enough.

我不理解的问题是在#include "header_a.hpp"周围使用#ifndef __HEADER_A_HPP__#endif.同事告诉我,这为夹杂物增加了第二层保护,但是我看不到如果第一层绝对完成了工作(或做到了吗?),那么第二层是多么有用.

The issue I don't understand is using #ifndef __HEADER_A_HPP__ and #endif around the #include "header_a.hpp". I'm told by the coworker that this adds a second layer of protection to inclusions but I fail to see how that second layer is even useful if the first layer absolutely does the job (or does it?).

我能想到的唯一好处是,它彻底阻止了链接程序费心查找文件.这是否是为了缩短编译时间(这没有被提及是有好处的),还是还有其他我看不到的东西在工作?

The only benefit I can come up with is that it outright stops the linker from bothering to find the file. Is this meant to improve compilation time (which was not mentioned as a benefit), or is there something else at work here that I am not seeing?

推荐答案

我敢肯定,添加另一个包含以下内容的包含保护措施是一种不好的做法:

I am pretty sure that it is a bad practice to add another include guard like:

#ifndef __HEADER_A_HPP__
#include "header_a.hpp"
#endif

以下是一些原因:

  1. 为避免重复包含,在头文件本身内添加一个常规的include防护就足够了.它做得很好.代替包含的另一个include Guard只会弄乱代码并降低可读性.

  1. To avoid double inclusion it is enough to add a usual include guard inside the header file itself. It does the job well. Another include guard in the place of inclusion just messes the code and reduces readability.

它添加了不必要的依赖项.如果您更改头文件中的包含保护,则必须在所有包含头文件的位置进行更改.

It adds unnecessary dependencies. If you change include guard inside the header file you have to change it in all places where the header is included.

与整个编译/链接过程相比,绝对不是最昂贵的操作,因此它几乎不会减少总构建时间.

It is definitely not the most expensive operation comparing the whole compilation/linkage process so it can hardly reduce the total build time.

任何有价值的编译器已经优化了文件级的include-guards .

这篇关于在C ++中使用双重包含保护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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