#pragma 一旦进入头护卫的原因是什么?
刚刚在
中看到了这一点,
#ifndef BOOST_ASIO_HPP
#define BOOST_ASIO_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
/// ....
#endif // BOOST_ASIO_HPP
忽略 _MSC_VER
预处理器检查,在中使用 #pragma Once
有什么好处这个案子?预处理器标头保护是否不能确保在所有情况下和所有平台上,标头内容仅包含
一次?
Just seen this inside <boost/asio.hpp>
#ifndef BOOST_ASIO_HPP
#define BOOST_ASIO_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
/// ....
#endif // BOOST_ASIO_HPP
Disregarding the _MSC_VER
preprocessor checks, what is the benefit of having the #pragma once
in this case? Doesn't the preprocessor header guard ensure in all cases and on all platforms, the header contents are only ever included
once?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
#pragma Once
指定编译器在编译源代码文件时将仅包含(打开)该文件一次。这可以减少构建时间,因为编译器不会在模块的第一个#include
之后打开和读取文件。如果您不
#pragma Once
,该文件将每次需要时打开,并且编译器将在#ifndef BOOST_ASIO_HPP
上停止解析它,如果已定义。#pragma once
specifies that the file will be included (opened) only once by the compiler when compiling a source code file. This can reduce build times as the compiler will not open and read the file after the first#include
of the module.If you don't
#pragma once
, the file will be opened each time it is needed and compiler will stop parsing it on#ifndef BOOST_ASIO_HPP
, if it has been defined.指定编译器在构建中仅包含(打开)一次文件。这可以减少构建时间,因为编译器在模块的第一个 #include 之后不会打开和读取文件
还有一个来自 所以
Specifies that the file will be included (opened) only once by the compiler in a build. This can reduce build times as the compiler will not open and read the file after the first #include of the module
And one more related question from SO
是的标头防护确保标头内容仅包含一次。但在这里您使用 #pragma 检查另一个定义而不是包含文件。
以下链接是 SO 中关于标头保护的现有问题。
标头防护的目的
Yes header guards ensures that the header contents are included only once. but here you are using #pragma for checking another definition and not include file.
The below link is existing question on header guards in SO.
Purpose of Header guards
#pragma Once
具有相同的目的,但包含防护旨在需要更深入的分析以确保文件仅包含一次 - 例如,除非编译器正确处理此类情况,否则它仍然需要打开文件并将其传递给预处理器,即使它之前已经包含过。
#pragma once
has the same purpose, but include guards are intended to require a deeper analysis to ensure a file is included exactly once - e.g.Unless the compiler does handle such cases correctly, it still needs to open the file and pass it through the preprocessor even though it has been included before.
您可以使用以下命令以标准方式重现
#pragma Once
的效果:尽管它更加冗长。正如其他人所说,它有助于缩短编译时间,因为不会搜索/打开文件,而不是打开文件并忽略其中的所有内容 - 文件仍然需要由预处理器解析。
You can reproduce the effect of the
#pragma once
in a standard way using the following:although it is much more verbose. As others have said, it helps with compilation times since the file is not searched for / opened instead of opening the file and ignoring everything inside it - the file still has to be parsed by the preprocessor.