在C和C++编程语言中,#pragma once是一个非标准但是被广泛支持的前置处理符号,会让所在的文件在一个单独的编译中只被包含一次。以此方式,#pragma once
提供类似include防范的目的,但是拥有较少的代码且能避免名称的碰撞。
示例
请参考include防范里其中一种状况的示例或其他的使用方法。如下:
- grandparent.h
#pragma once
struct foo
{
int member;
};
- parent.h
#include "grandparent.h"
- child.c
#include "grandparent.h"
#include "parent.h"
优缺点
使用#pragma once
代替include防范将加快编译速度,因为这是一种高阶的机制;编译器会自动比对文件名称或inode而不需要在头文件去判断#ifndef
和#endif
。
另一方面,部分编译器,例如GCC、clang等,也包含特别的代码来识别和有效率的管理include防范。因此使用#pragma once
并不会得到明显的加速。[1][2][3]
此外,因为编译器自己必须承担管理#pragma once
,它不必定义新的指令名称,例如在include防范文章示例的H_GRANDFATHER
。这能排除名称碰撞的风险,意思就是至少第一次包含头文件不会再有错误。
然而,这种高阶的管理有好也有坏;设计者必须依赖编译器正确的管理#pragma once
。编译器如果犯错,例如没有辨认出在相同文件中的两个不同符号链接名称指针,此时编译会错误。编译器对于#pragma once
可能包含相关的bug LCC-Win32 2004年[1][2]和GCC 1998年。[3](页面存档备份,存于互联网档案馆)2005年,GCC文件中将#pragma once
列为“已淘汰”的特性。[4](页面存档备份,存于互联网档案馆)随着gcc 3.4的发布,gcc解决了#pragma once中的一些问题(主要是跟符号链接和硬链接有关),并且去掉了#pragma once的“已淘汰”的标签。[5](页面存档备份,存于互联网档案馆)
编译器支持
参考文献
外部链接
Wikiwand in your browser!
Seamless Wikipedia browsing. On steroids.
Every time you click a link to Wikipedia, Wiktionary or Wikiquote in your browser's search results, it will show the modern Wikiwand interface.
Wikiwand extension is a five stars, simple, with minimum permission required to keep your browsing private, safe and transparent.