c++ - 关于包含带有 guard 的头文件

标签 c++

我正在阅读一本关于 Applied C++ 的书。

Include guards will prevent a header file from being included more than once during the compilation of source file. Your symbol names should be unique, and we recommend choosing the name based on the name of the file. For example, our file, cache.h contains this include guard.

#ifndef _cache_h_
 #define _cache_h_
 ...
 #endif // _cache_h_

Lakos describes using redundant include guards to speed up compilation. See [Lakos96]. For large projects, it takes times to open each file, only to find that the include guard symbol is already defined (i.e., the file has already been included). The effects on compilation time can be dramatic, and Lakos shows a possible 20x increase in compilation times when only standard include guards are used.

[Lakos96]: LargeScale C++ software design.

我没有 Lakos96 引用书来引用概念,所以在这里寻求帮助。

我对以上文字的问题是

  1. 作者所说的“对于大型项目,打开每个文件都需要时间,才发现包含保护符号已经定义”是什么意思?

  2. 作者所说的“使用标准包含防护时”是什么意思?

感谢您的宝贵时间和帮助。

最佳答案

来自 C++ 编码标准(Sutter、Alexandrescu)

Many modern C++ compilers recognize header guards automatically (see Item 24) and don't even open the same header twice. Some also offer precompiled headers, which help to ensure that often-used, seldom-changed headers will not be parsed often

因此,我认为这些建议已经过时(除非您仍在使用一些非常过时的编译器)。

关于您的问题:

  1. 这意味着:打开一个不需要的文件(因为它已经被包含;你会知道,因为包含保护已经被定义)是昂贵的;如果您多次执行此操作(如果您的项目中有数百个文件,则可能会发生这种情况)。
  2. 与使用非冗余编译保护相反。

什么是冗余编译保护?

A naive compiler will reload the file every time it's included. To avoid that, put RedundantIncludeGuards around the include: header.h

 #ifndef HEADER_H_
  #define HEADER_H_
  // declarations
  #endif

foo.c

 #ifndef HEADER_H_
  #include "header.h"
  #endif

阅读更多 here .您的引用资料声称,通过这样做,您在编译期间的速度可以比 foo.c 仅执行时快 20%

 #include "header.h"

关于c++ - 关于包含带有 guard 的头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17805541/

相关文章:

c++ - Ubuntu 14.04 中的 OpenGL 4.3 开发设置

c++ - 单例设计模式中复制构造函数和赋值运算符的使用

c++ - 关于抽象类设计

c++ - 如何取消设置 std::cout 精度?

C++ 忽略并清除缓冲区

c++ - 两个 Actor 的交集 - Vtk

C++ cout 副作用排序

C++ 沙盒动态库

c++ - 为考试而死记硬背——我错过了什么(C++ 字符串操作)

c++ - 如何在 c/c++ 中将 JSON 文件转换为 UTF-8 格式?