448

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?

1
  • 3
    After asking a similar question, I found out that #pragma once appears to avoid some class view issues in VS 2008. I'm in the process of getting rid of include guards and replacing them all with #pragma once for this reason. Commented Feb 2, 2011 at 13:54

16 Answers 16

409

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

Sign up to request clarification or add additional context in comments.

15 Comments

But you can also have two files with the same name in different locations without having to bother creating different #define NAMES, which is iften in the form of HEADERFILENAME_H
You can also have two or more files with the the same #define WHATEVER which causes no end of fun, which is the reason I would favour using pragma once.
Not persuasive... Change the build system to one that doesn't copy files around but uses symlinks instead, or include the same file only from one location in each translation unit. Sounds more like your infrastructure is a mess that has to be reorganized.
If you use symlinks (e.g. to synchronise header files in a development directory, with your include directory) then #pragma once may not identify them as the same file causing potential double includes. This problem caused me hard to find errors in msvc
I'm not surprised since symlinking is rare on windows... Regardless, over a decade later, I (still) think that copying or symlinking headers as part of your build is bad practice. You should only have them in one place, and should only ever include it using a canonical path. There are better arguments against #pragma once.
And if you have different files with the same name on different directories, the #ifdef approach will think they are the same file. So there is a drawback for one, and there is a drawback for the other.
@rxantos, if the files differ the #ifdef macro value can also differ.
|
280

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.

20 Comments

It shouldn't be any slower at all (with GCC anyway).
It isn't implemented that way. Instead, if the file starts with an #ifndef the first time and ends with an #endif, gcc remembers it and always skips that include in the future without even bothering to open the file.
#pragma once is generally faster because file is not being preprocessed. ifndef/define/endif requires preprocessing anyway, because after this block you can have something compilable (theoretically)
GCC docs on the guard macro optimization: gcc.gnu.org/onlinedocs/cppinternals/Guard-Macros.html
To use include guards, there is the extra requirement that you must define a new symbol such as #ifndef FOO_BAR_H, normally for a file such as "foo_bar.h". If you later rename this file, should you adjust the include guards accordingly to be consistent with this convention? Also, if you have two distinct foo_bar.h's in two different places in your code tree, you have to think of two different symbols for each one. Short answer is to use #pragma once and if you really need to compile in an environment that doesn't support it, then go ahead and add include guards for that environment.
|
47

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.

Comments

32

GCC supports #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.

TL;DR: #pragma once is easier to use.

Comments

12

I use it and I'm happy with it, as I have to type much less to make a new header. It worked fine for me in three platforms: Windows, Mac and Linux.

I don't have any performance information but I believe that the difference between #pragma and the include guard will be nothing comparing to the slowness of parsing the C++ grammar. That's the real problem. Try to compile the same number of files and lines with a C# compiler for example, to see the difference.

In the end, using the guard or the pragma, won't matter at all.

2 Comments

I dislike #pragma once, but I appreciate you pointing out the relative benefits... C++ parsing is much more expensive than anything else, in a "normal" operating environment. Nobody compiles from a remote filesystem if compile-times are an issue.
Re C++ parsing slowness vs. C#. In C# you don't have to parse (literally) thousands of LOC of header files (iostream, anyone?) for each tiny C++ file. Use precompiled headers to make this problem smaller, however
11

Using '#pragma once' might not have any effect (it is not supported everywhere - though it is increasingly widely supported), so you need to use the conditional compilation code anyway, in which case, why bother with '#pragma once'? The compiler probably optimizes it anyway. It does depend on your target platforms, though. If all your targets support it, then go ahead and use it - but it should be a conscious decision because all hell will break loose if you only use the pragma and then port to a compiler that does not support it.

1 Comment

I disagree that you have to support guards anyway. If you use #pragma once (or guards) this is because it raises some conflicts without them. So if it is not supported by your chain tool the project just won't compile and you are exactly in the same kind of situation than when you want to compile some ansi C on an old K&R compiler. You just have to get a more up to date chaintool or change code to add some guards. All hell breaking would be if program was compiling but failed to work.
7

The performance benefit is from not having to reopen the file once the #pragma once have been read. With guards, the compiler have to open the file (that can be costly in time) to get the information that it shouldn't include it's content again.

That is theory only because some compilers will automatically not open files that didn't have any read code in, for each compilation unit.

Anyway, it's not the case for all compilers, so ideally #pragma once have to be avoided for cross-platform code has it's not standard at all / have no standardized definition and effect. However, practically, it's really better than guards.

In the end, the better suggestion you can get to be sure to have the best speed from your compiler without having to check the behavior of each compiler in this case, is to use both pragma once and guards.

#ifndef NR_TEST_H #define NR_TEST_H #pragma once #include "Thing.h" namespace MyApp { // ... } #endif 

That way you get the best of both (cross-platform and help compilation speed).

As it's longer to type, I personally use a tool to help generate all that in a very wick way (Visual Assist X).

3 Comments

Does Visual Studio not optimize #include guards as-is? Other (better?) compiler do so, and I imagine it is quite easy.
Why do you put the pragma after the ifndef? Is there a benefit?
@user1095108 Some compilers will use the header guards as delimiter to know if the file contain only code that have to be instantiated once. If some code is outside the header guards, then the whole file might be considered maybe instantiable more than once. If that same compiler don't support pragma once, then it will ignore that instruction. Therefore, putting the pragma once inside the header guards is the most generic way to make sure that at least header guards can be "optimized".
6

Not always.

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52566 has a nice example of two files meant to both be included, but mistakenly thought to be identical because of identical timestamps and content (not identical file name).

2 Comments

That would be a bug in the compiler. (trying to take a shortcut it shouldn't take).
#pragma once is nonstandard, so whatever a compiler decides on doing is "correct". Of course, then we can start talking about what is "expected" and what is "useful".
4

I use #ifndef/#define include guards using symbols that incorporate a UUID like this:

#ifndef ARRAY__H_81945CB3_AEBB_471F_AC97_AB6C8B220314 #define ARRAY__H_81945CB3_AEBB_471F_AC97_AB6C8B220314 /* include guard */ #endif 

I'v always used editors that were able to generate the UUIDs automatically. This prevents name clash with files with the same base name from other libraries, and detects if the exact same file is placed in multiple locations inside the file system.

The down-side is the increase table size since the symbols are much bigger but I have not yet seen problems with it.

4 Comments

It's also possible to incorporate other elements in the name, such as the library name, the organization name, the creation date. These would be generated automatically and would reduce the probability, already very small, of a clash.
If anyone want to see how this can be done in Emacs, take a look at my PEL project on GitHub, specifically the PEL manual section on C headers as well as the pel-uuid.el and pel-skels-c.el files.
Hi @sammonius, thanks for the comment. I'm not sure I understand, do you have an example? The include guard macro is always used to check if something was already included, to prevent multiple or circular inclusion of a file by the C pre-processor. Do you mean that code would expect a specific symbol to identify whether something was already included without looking into the header file to see what symbol is actually used?
Ok @sammonius, then you may want to delete your comment and I'll delete mine as they don't provide useful extra info
3

Today old-school include guards are as fast as a #pragma once. Even if the compiler doesn't treat them specially, it will still stop when it sees #ifndef WHATEVER and WHATEVER is defined. Opening a file is dirt cheap today. Even if there were to be an improvement, it would be in the order of miliseconds.

I simply just don't use #pragma once, as it has no benefit. To avoid clashing with other include guards I use something like: CI_APP_MODULE_FILE_H --> CI = Company Initials; APP = Application name; the rest is self-explanatory.

6 Comments

Isn't the benefit that it's much less typing?
Do note that some milliseconds a hundred thousand times are some minutes, though. Large projects consist of ten thousands of files including tens of headers each. Given present-day many-core CPUs, input/output, in particular opening many small files, is one of the major bottlenecks.
"Today old-school include guards are as fast as a #pragma once." Today, and also many many years ago. The oldest docs on the GCC site are for 2.95 from 2001 and optimising include guards was not new then. It isn't a recent optimisation.
The main benefit is that include guards are error-prone and wordy. It's too easy to have two different files with identical names in different directories (and the include guards might be the same symbol), or to make copy-paste errors while copying include guards. Pragma once is less error-prone, and works on all the major PC platforms. If you can use it, it is better style.
Opening a file is dirt cheap today. Oh hoh hoh. Try to build a large project from a network mount sometime :)
|
3

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 #pragma once.

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.

Comments

3

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.

5 Comments

Could C++ templates solve the problem? I rarely find any valid need for macros because of how C++ templates.
Our long term professional experience is that using mature language, software and tools infrastructure all the time gives us as service providers (Embedded Systems) a huge advantage in productivity and flexibility. Competitors developing C++ based embedded systems software and stacks instead might find some of their developers more happy at work. But we usually outperform them time-to-market, functionality and flexibility-wise multiple times. Nether underestimate productivity gains from using one and the same tool over and over again. Web-Devs instead do suffer from ways to many Frameworks.
A note though: isn't including guards/#pragma once in every header file against the DRY principle itself. I can see your point in the X-Macro feature, but it is not the main use of include, shouldn't it be the other way around like header unguard/#pragma multi if we were to stick with DRY?
DRY stands for "Dont repeat YOURSELF". Its about the human. What the machine is doing, has nothing to do with that paradigm. C++ templates repeat a lot, C-compilers do that as well (e.g. loop unrolling) and every Computer is repeating nearly everything unbelievable often and fast.
Very good point @Marcel. The X-Macro concept is quite useful indeed and to create a header file that is meant to be used in that scheme requires that the header file be allowed to be included more than once. As always, overall understanding is important. I would tend to distinguish headers that are written as X-Macro and the others, the classical headers that are meant to be included once. Probably using a naming convention that would allow editor tools that generate the boiling plate code of those files to distinguish the purpose of the file, and the code reader too.
2

Using gcc 3.4 and 4.1 on very large trees (sometimes making use of distcc), I have yet to see any speed up when using #pragma once in lieu of, or in combination with standard include guards.

I really don't see how its worth potentially confusing older versions of gcc, or even other compilers since there's no real savings. I have not tried all of the various de-linters, but I'm willing to bet it will confuse many of them.

I too wish it had been adopted early on, but I can see the argument "Why do we need that when ifndef works perfectly fine?". Given C's many dark corners and complexities, include guards are one of the easiest, self explaining things. If you have even a small knowledge of how the preprocessor works, they should be self explanatory.

If you do observe a significant speed up, however, please update your question.

2 Comments

True, if you want to support older compilers. But not relevant if your code requires let's say C++17, as all C++17 compilers support #pragma once AFAIK.
@Jens 14 years after writing this I tend to agree ;)
1

The main difference is that the compiler had to open the header file to read the include guard. In comparison, pragma once causes the compiler to keep track of the file and not do any file IO when it comes across another include for the same file. While that may sound negligible, it can easily scale up with huge projects, especially ones without good header include disciplines.

That said, these days compilers (including GCC) are smart enough to treat include guards like pragma once. i.e. they dont open the file and avoid the file IO penalty.

In compilers that dont support pragma I've seen manual implementations that are a little cumbersome..

#ifdef FOO_H #include "foo.h" #endif 

I personally like #pragma once approach as it avoids the hassle of naming collisions and potential typo errors. It's also more elegant code by comparison. That said, for portable code, it shouldn't hurt to have both unless the compiler complains about it.

5 Comments

"That said, these days compilers (including GCC) are smart enough to treat include guards like pragma once." They been doing it for decades, maybe longer than #pragma once has existed!
Think you misunderstood me. I meant to say prior to pragma once, all compilers would incur multiple IO penanties for the same h file included multiple times during the preprocessor stage. Modern implementations end up using better caching of files in the preprocessor stage. Regardless, without pragmas, the preprocessor stage ends up still including everything outside of the include guards. With pragma once, the whole file is left out. From that standpoint, pragma is still advantageous.
No, that's wrong, decent compilers leave the whole file out even without #pragma once, they don't open the file a second time and they don't even look at it a second time, see gcc.gnu.org/onlinedocs/cpp/Once-Only-Headers.html (this is nothing to do with caching).
From your link, seems like the optimization happens only in cpp. Regardless, caching does come into play. How does the preprocessor know to include code outside of the guards. Example... extern int foo; #ifndef INC_GUARD #define INC_GUARD class ClassInHeader{}; #endif In this case the preprocessor will have to include extern int foo; multiple times if you include the same file multiple times. End of the day, not much point arguing over this as long as we understand the difference between #pragma once and include guards and how various compilers behave with both of them :)
It doesn't apply the optimisation in that, obviously.
1

Just about the faster compilation: If you use include guards using ifdef/define, in theory the compiler would have to read the header file and check every time it is included. But in practice, the compiler sees that you have the structure “white space” - “#if condition” - lots of code - “#endif” - “white space”. With tha pattern present, the compiler will remember just the path of the file, and the condition. If it encounters another #include for the same file path, it just checks the condition and only opens the file if at this point the condition is false.

This works, whether you use an include guard, or if the whole file is not used depending on some feature flag. And it works if you manually undefine the include guard because you want it included twice. So the time difference compared to “pragma once” is minimal. And this is so common today, you really don’t have to use “pragma once” for compiler performance.

Comments

1

As of today, #pragma once is supported by all major compilers, either on *nix or Windows. So unless you're writing some ultra-portable code or targeting a specific outdated niche platform (e.g. some old embedded), you can safely resort to #pragma once as your mechanism of choice.

Regardless, there's no point in using #pragma once in combination with an include guard anymore. Compilers do detect the standard use of include guards and avoid reading the file multiple times. So if you choose using an include guard for portability, #pragma once becomes redundant.

I do often use #pragma once myself, partly out of habit and partly for brevity. However, there are valid reasons you may want to use include guards instead, besides portability:

  • Include guards allow checking whether some headers were included or not. You can do that by checking if that header's include guard is defined or not:

     #if defined(__gl_h_) || defined(__GL_H__) #error Attempt to include auto-generated header after including gl.h #endif 
  • Single-header libraries: when after the guarded public API section in the header, you provide the implementation of the API that the user can enable using a different define:

     #ifndef STBI_INCLUDE_STB_IMAGE_H #define STBI_INCLUDE_STB_IMAGE_H /* ... public API ... */ #endif #ifdef STB_IMAGE_IMPLEMENTATION /* ... private implementation of the API ... */ #endif 

    If you used #pragma once, the implementation would need to go in a separate file.

  • #pragma once may not play well with symlinks or multiple copies of the file. Even though I strongly recommend that you ever include the same header using the same canonical path, it may still happen in some scenarios that both copies are included and the build fails, as pointed out by commenters above.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.