正确使用#include语句的双引号形式和角括号形式


正确使用#include语句的双引号形式和角括号形式文章插图
SF.12: Prefer the quoted form of #include for files relative to the including file and the angle bracket form everywhere elseSF.12:使用双引号形式的#include语句包含相对路径中的文件 , 用角括号形式包含所有其他位置的文件Reason(原因)
The standard provides flexibility for compilers to implement the two forms of #include selected using the angle (<>) or quoted ("") syntax. Vendors take advantage of this and use different search algorithms and methods for specifying the include path.
这个标准为编译器提供了灵活性以便使用角括号(<>)或双引号(“”)语法处理两种形式的#inlcude语法 。 编译器厂家可以通过这个标准获得便利以便针对定义的包含路径使用不同的搜索算法和方法 。
Nevertheless, the guidance is to use the quoted form for including files that exist at a relative path to the file containing the #include statement (from within the same component or project) and to use the angle bracket form everywhere else, where possible. This encourages being clear about the locality of the file relative to files that include it, or scenarios where the different search algorithm is required. It makes it easy to understand at a glance whether a header is being included from a local relative file versus a standard library header or a header from the alternate search path (e.g. a header from another library or a common set of includes).
尽管如此 , 原则是用引号形式引入存在于使用#include语句的文件相对路径中的(属于相同组件或项目的)文件 , 而使用角括号引入任何其他场所的文件(如果可能) 。 这鼓励明确被包含文件和包含文件的相对位置 , 或者在需要不同检索算法时的过程 。 这么做的结果是可以很容易快速判明头文件是引自相对路径还是标准库 , 亦或是可选的检索路径(例如来自其他库或通用集合) 。
Example(示例)
// foo.cpp:#include// From the standard library, requires the <> form#include// A file that is not locally relative, included from another library; use the <> form#include "foo.h"// A file locally relative to foo.cpp in the same project, use the "" form#include "foo_utils/utils.h"// A file locally relative to foo.cpp in the same project, use the "" form#include // A file in the same project located via a search path, use the <> formNote(注意)
Failing to follow this results in difficult to diagnose errors due to picking up the wrong file by incorrectly specifying the scope when it is included. For example, in a typical case where the #include "" search algorithm might search for a file existing at a local relative path first, then using this form to refer to a file that is not locally relative could mean that if a file ever comes into existence at the local relative path (e.g. the including file is moved to a new location), it will now be found ahead of the previous include file and the set of includes will have been changed in an unexpected way.
不遵守本准则的结果是难以判明由于包含文件时错误定义了范围而选中了其他文件而引发的错误 。 例如一个典型的场景是当#include""检索算法首先检索本地相对路径时 , 使用这种形式参照一个非本地相对路径中的文件可能就意味着如果一个文件出现在在本地相对路径中(例如包含文件被移动到新位置) , 它将在期待的包含文件之前被发现 , 而且包含组合将会以出乎意料的方式被修改 。


推荐阅读