What does #pragma once mean in C? [duplicate]

随声附和 提交于 2019-12-02 19:26:58
Ptival

http://gcc.gnu.org/onlinedocs/cpp/Pragmas.html

-- also, it's pragma, not pragama, and a search for pragma on Stack Overflow would have helped you

cf. Use of #pragma in C and many others...

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.

See the Wikipedia article for further details.

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.

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

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 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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!