问题描述
引自 Microsoft 文档,没有在同一文件中同时使用 #include 守卫习惯用法和 #pragma once 的优势.
之前关于 stackoverflow 的相关问题的答案也证实了两者兼而有之是毫无意义的.例如,见下文:
Answers to previous related questions on stackoverflow also confirm that it is pointless to have both. See below, for instance:
标题守卫和编译指示一次
boost
库的 vector.hpp
文件是这样开始的:
The boost
library's vector.hpp
file, however, starts thus:
#ifndef BOOST_ASSIGN_STD_VECTOR_HPP
#define BOOST_ASSIGN_STD_VECTOR_HPP
#if defined(_MSC_VER)
# pragma once
#endif
...
#endif
也就是说,它既包括守卫习语也包括 pragma once.有什么原因为什么boost头文件有两个?
That is, it includes both the guard idiom as well as the pragma once. Is there any reason why boost header files have both?
推荐答案
从技术上讲#pragma once
不是标准的 C++,而标头保护是.如果两者兼而有之,它们就不会相互冲突.
Technically #pragma once
is not standard C++, whereas header guards are. They will not conflict with each other if you have both.
boost 可能兼具两者的原因,正如 #if defined(_MSC_VER)
所暗示的那样,如果你不使用 MSVC,那么你需要一些东西来采取行动作为你的头球后卫,所以他们回到另一种方法.
The reason boost likely has both, as alluded to by the #if defined(_MSC_VER)
is that if you're not using MSVC then you need something to act as your header guard, so they fall back to the other method.
由于 boost 力求跨平台,他们试图确保他们的代码在不支持 #pragma once
的编译器上工作,尽管我能想到的所有大型现代编译器都支持它,如在维基百科中列举.
Since boost strives to be cross-platform they are trying to ensure their code works on compilers that don't support #pragma once
, though all of the big modern compilers I can think of do support it, as enumerated on wikipedia.
这篇关于在同一个头文件中包含 guard 和 #pragma once的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!