1.原始问题：Is #pragma once a safe include guard?
I’ve read that there is some compiler optimization when using
#pragma once which can result in faster compilation. I recognize that is non-standard, and thus could pose a cross-platform compatibility issue.
Is this something that is supported by most modern compilers on non-windows platforms (gcc)?
I want to avoid platform compilation issues, but also want to avoid the extra work of fallback guards:
#pragma once #ifndef HEADER_H #define HEADER_H ... #endif // HEADER_H
Should I be concerned? Should I expend any further mental energy on this?
#pragma once should work on any modern compiler, but I don’t see any reason not to use a standard
#ifndef include guard. It works just fine. The one caveat is that GCC didn’t support
#pragma once before version 3.4.
I also found that, at least on GCC, it recognizes the standard
#ifndef include guard and optimizes it, so it shouldn’t be much slower than
Additional note to the people thinking that an automatic one-time-only inclusion of header files is always desired: I build code generators using double or multiple inclusion of header files since decades. Especially for generation of protocol library stubs I find it very comfortable to have a extremely portable and powerful code generator with no additional tools and languages. I’m not the only developer using this scheme as this blogs X-Macros show. This wouldn’t be possible to do without the missing automatic guarding.
If we use msvc or Qt (up to Qt 4.5), since GCC(up to 3.4) , msvc both support
#pragma once, I can see no reason for not using
Source file name usually same equal class name, and we know, sometime we need refactor, to rename class name, then we had to change the
#include XXXX also, so I think manual maintain the
#include xxxxx is not a smart work. even with Visual Assist X extension, maintain the “xxxx” is not a necessary work.
I don’t know about any performance benefits but it certainly works. I use it in all my C++ projects (granted I am using the MS compiler). I find it to be more effective than using
#ifndef HEADERNAME_H #define HEADERNAME_H ... #endif
It does the same job and doesn’t populate the preprocessor with additional macros.
#pragma once officially as of version 3.4.
#pragma once since 3.4, see http://en.wikipedia.org/wiki/Pragma_once for further compiler support.
The big upside I see on using
#pragma once as opposed to include guards is to avoid copy/paste errors.
Let’s face it: most of us hardly start a new header file from scratch, but rather just copy an existing one and modify it to our needs. It is much easier to create a working template using
#pragma once instead of include guards. The less I have to modify the template, the less I am likely to run into errors. Having the same include guard in different files leads to strange compiler errors and it takes some time to figure out what went wrong.
#pragma once is easier to use.