C语言 #pragma once 在 C 中是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5776910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 08:29:15  来源:igfitidea点击:

What does #pragma once mean in C?

cpragma

提问by wireshark

Possible Duplicate:
#pragma - help understanding

可能的重复:
#pragma - 帮助理解

I saw the pragmamany times,but always confused, anyone knows what it does?Is it windows only?

看了pragma很多遍了,还是一头雾水,有谁知道是做什么用的吗?是不是只有windows?

回答by helpermethod

In the C and C++ programming languages, #pragma once is a non-standard but widely supported preprocessor directive designed to cause the current source file to be included only once in a single compilation. Thus, #pragma once serves the same purpose as #include guards, but with several advantages, including: less code, avoiding name clashes, and improved compile speed.

在 C 和 C++ 编程语言中,#pragma once 是一个非标准但受到广泛支持的预处理器指令,旨在使当前源文件在单个编译中只包含一次。因此,#pragma 曾经与#include 守卫服务相同的目的,但具有几个优点,包括:更少的代码、避免名称冲突和提高编译速度。

See the Wikipediaarticle for further details.

有关更多详细信息,请参阅维基百科文章。

回答by Alex Kremer

It's used to replace the following preprocessor code:

它用于替换以下预处理器代码:

#ifndef _MYHEADER_H_
#define _MYHEADER_H_
...
#endif

A good convention is adding both to support legacy compilers (which is rare tho):

一个好的约定是添加两者以支持遗留编译器(这种情况很少见):

#pragma once
#ifndef _MYHEADER_H_
#define _MYHEADER_H_
...
#endif

So if #pragma once fails the old method will still work.

因此,如果#pragma once 失败,旧方法仍然有效。

回答by Alex Kremer

Generally, the #pragmadirectives are intended for implementing compiler-specific preprocessor instructions. They are not standardized, so you shouldn't rely on them too heavily.

通常,这些#pragma指令旨在实现特定于编译器的预处理器指令。它们没有标准化,因此您不应过分依赖它们。

In this case, #pragma once's purpose is to replace the include guards that you use in header files to avoid multiple inclusion. It works a little faster on the compilers that support it, so it may reduce the compilation time on large projects with a lot of header files that are #include'ed frequently.

在这种情况下,#pragma once的目的是替换您在头文件中使用的包含保护以避免多次包含。它在支持它的编译器上运行得更快一些,因此它可以减少大型项目的编译时间,这些项目有很多#include经常被'ed的头文件。

回答by danny_23

pragma is a directive to the preprocessor. It is usually used to provide some additional control during the compilation. For example do not include the same header file code. There is a lot of different directives. The answer depends on what follows the pragma word.

pragma 是预处理器的指令。它通常用于在编译期间提供一些额外的控制。例如不要包含相同的头文件代码。有很多不同的指令。答案取决于 pragma 词后面的内容。