Is #pragma once a safe include guard?
#pragma once
does have one drawback (other than being non-standard) and that is if you have the same file in different locations (we have this because our build system copies files around) then the compiler will think these are different files.
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.
GCC supports #pragma once
officially as of version 3.4.
Using #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 #pragma once
.
I wish #pragma once
(or something like it) had been in the standard. Include guards aren't a real big deal (but they do seem to be a little difficult to explain to people learning the language), but it seems like a minor annoyance that could have been avoided.
In fact, since 99.98% of the time, the #pragma once
behavior is the desired behavior, it would have been nice if preventing multiple inclusion of a header was automatically handled by the compiler, with a #pragma
or something to allow double including.
But we have what we have (except that you might not have #pragma once
).