#pragma 曾经是 C++11 标准的一部分吗?

2022-01-11 00:00:00 macros c++ c++11 header-files c++14

传统上,避免在 C++ 中包含多个标头的标准和可移植方法是使用 #ifndef - #define - #endif预编译器指令方案,也称为 宏守卫方案(见下面的代码片段).

Traditionally, the standard and portable way to avoid multiple header inclusions in C++ was/is to use the #ifndef - #define - #endifpre-compiler directives scheme also called macro-guard scheme (see code snippet below).

#ifndef MY_HEADER_HPP
#define MY_HEADER_HPP
...
#endif

然而,在大多数实现/编译器(见下图)中,有一个更优雅"的替代方案,其用途与称为 #pragma once.#pragma once 与宏保护方案相比有几个优点,包括更少的代码、避免名称冲突以及有时提高编译速度.

In most implementations/compilers (see picture below) however, there's a more "elegant" alternative that serves the same purpose as the macro-guard scheme called #pragma once. #pragma once has several advantages compared to the macro-guard scheme, including less code, avoidance of name clashes, and sometimes improved compile speed.

做了一些研究,我意识到虽然几乎所有已知的编译器都支持 #pragma once 指令,但对于 #pragma once 指令是否是C++11 标准与否.

Doing some research, I realized that although #pragma once directive is supported by almost all known compilers, there's a turbidness on whether #pragma once directive is part of the C++11 standard or not.

  • 有人能澄清一下 #pragma once 指令是否属于 C++11 标准吗?
  • 如果它不是 C++11 标准的一部分,是否有计划将其包含在以后的版本中(例如 C++14 或更高版本)?
  • 如果有人能进一步详细说明使用其中一种技术的优缺点(例如,macro-guard 与 #pragma once),那就太好了.
  • Could someone clarify whether #pragma once directive is part of the C++11 standard or not?
  • If it's not part of the C++11 standard, are there any plans on including it on later releases (e.g., C++14 or later)?
  • It would also be nice if someone could further elaborate on the advantages/disadvantages in using either one of the techniques (i.e., macro-guard versus #pragma once).

推荐答案

#pragma once 不是标准.它是一种普遍的(但不是通用)扩展,可以使用

#pragma once is not standard. It is a widespread (but not universal) extension, which can be used

  • 如果您对便携性的担忧有限,并且
  • 您可以确保所有包含文件始终位于本地磁盘上.

它被考虑标准化,但被拒绝,因为它无法可靠实施.(当你出现问题时可以通过几个不同的远程挂载访问文件.)

It was considered for standardization, but rejected because it cannot be implemented reliably. (The problems occur when you have files accessible through several different remote mounts.)

确保没有包含保护是相当容易的单一发展中的冲突.对于图书馆,可能被许多不同的开发使用,显??而易见的解决方案是为包含防护生成大量随机字符当你创建它时.(可以设置一个好的编辑器来执行此操作每当你打开一个新的标题.)但即使没有这个,我还没有遇到任何冲突的问题图书馆.

It's fairly easy to ensure that there are no include guard conflicts within a single development. For libraries, which may be used by many different developments, the obvious solution is to generate a lot of random characters for the include guard when you create it. (A good editor can be set up to do this for you whenever you open a new header.) But even without this, I've yet to encounter any problems with conflicts between libraries.

相关文章