C++核心准则​SF.8:为所有的.h文件使用包含监护​

时间:2022-07-27
本文章向大家介绍C++核心准则​SF.8:为所有的.h文件使用包含监护​,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

SF.8: Use #include guards for all .h files

SF.8:为所有的.h文件使用包含监护

Reason(原因)

To avoid files being #included several times.

为了避免文件被多次包含。

In order to avoid include guard collisions, do not just name the guard after the filename. Be sure to also include a key and good differentiator, such as the name of library or component the header file is part of.

为了避免包含监护发生冲突,不要只用文件名作为监护。保证同时包含一个键值和良好的区分信息,例如库名或者头文件所属的部件名。

Example(示例)

// file foobar.h:
#ifndef LIBRARY_FOOBAR_H
#define LIBRARY_FOOBAR_H
// ... declarations ...
#endif // LIBRARY_FOOBAR_H
Enforcement(实施建议)

Flag .h files without #include guards.

标记所有没有包含监护的头文件。

Note(注意)

Some implementations offer vendor extensions like #pragma once as alternative to include guards. It is not standard and it is not portable. It injects the hosting machine's filesystem semantics into your program, in addition to locking you down to a vendor. Our recommendation is to write in ISO C++: See rule P.2.

作为包含监护的代替手段,有些C++实现提供某些厂家扩展,例如#pragmaonce。这不是标准做法而且不可移植。它向你的程序注入了宿主机器的文件系统语义,另外将你锁定到这个厂家。我们的建议被写入了ISO C++中。参见规则P.2

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf8-use-include-guards-for-all-h-files