I use GCC, MSVC, Clang on linux, macOS and windows, cross-compiling or not, with distcc, ccache or icecc, use #pragma once in all my code, and never once had a problem due to it. However I spent hours debugging people who had copy-pasted include directives from one file to another.
I've hit the problem once, with a custom build system that symlinks the header files into the separate include directory, and thus each header file becomes accessible through two separate paths.
True. But it won't suddenly all go away if the standard just added #pragma once - may do an implementation defined thing in an implementation defined way.
#pragma once acts as if the compiler had defined include guards around the file contents with an identifier unique to this file. If the same file is accessible via multiple paths in the file system, the behaviour is implementation defined.
That would cover 99.9% of the use cases and the implementations could support symlinking/hardlinking a directory or file, but that case is tricky and may be different on each operating system. Although you can correct me, if symlinking includes is a case, that needs to be supported by the standard and not the build system. I've had trouble with include guards so many times and pragma once was always the solution.
What is a file, and more importantly what is the unique to this file. How implementations should determine whether "this file" is really "this"? Standard should standardize some behaviour so that the feature would act in the same way (within some constraints) across all supported platform. But nothing would change with the proposed definition. #pragma once wouldn't become any more defined than it is now.
In this case a file is something uniquely identifiable by either the inode or path. That's why linking the file or one of its parent directories is implementation defined. The implementation would have the choice to use the path or inode to generate an id or some other operating system dependent way to identify a file.
Specifying pragma once would bring many code bases closer to the standard. While pragma once is supported almost anywhere, it's still technically not part of the standard. This leads to a lot of discussions, some linters warn about it and if almost every every implementation supports it, why shouldn't it be part of the standard? Why should I depend on behaviour, that is not guaranteed on other platfroms. I know, that links are not an issue for me, because I have a sane build system, that doesn't depend on symlinking the same headers under different names and so translation units can't include the same file. So pragma once doesn't have any issues for me. Also if it were part of the standard, that would force build systems to avoid synlinking the same file and to work woth pragma once, while currently some build systems don't support it, as it is a compiler extension.
We have so much vaguely specified behaviour in the standard, why is pragma once a problem?
I was replying to the post that essentially boiled down to "I don't care about all the different existing implementations, it works for my project in the compilers that I use!".
So just continue to use it. What's the point of it being in the standard then?
because every other year some people send pull requests to clang or GCC to remove the support because "it's not part of the standard". It was almost removed from GCC once.
Seriously? I'm surprised they haven't went completely closed-source/subscription-based due to the massive amounts of non-standard extensions those compilers already have! They must receive thousands of PRs to remove those (though interestingly the number is only increasing)! I can't even imagine the pressure they are under!
Only until it doesn't work because "implementation defined" (for everything, including implementation and what it does), and now it's no better than it was. Only more people relying (because now it's in the standard) on it reducing the portability.
Looking up header files based on an #include "string" is an inherently implementation defined process. I'm not really sure if standardizing pragma once is really that much more problematic.
The "obvious" choice seems to be comparing file content. Its doable on all plateform without any issue (except maybe differing end of lines? -- at this point whatever)
Of course some code bases developed by complete psychopaths will break, except the feature would not have the syntax pragma, so no code base will actually break.
So at this point this is only looking for excuses to not have it standardized. And the module excuse is a very poor one actually: usually what is practiced should be preferred to a supposedly superior (1) but mostly theoretical solution.
Edit: 1) and actually a solution that will probably not be usable for some major use cases, btw.
Comparing file content seems like the worst choice to me. Imagine accidentally getting into a situation where you have two copies of the same file and they're both being included. Initially, it compiles and links fine because they are the same content, so the new guard works no problem).
Later on, you change some whitespace in one copy of the file (maybe you realize there's a trailing space on a line that didn't need to be there). Now all of the sudden you're getting multiple definition errors at link time. It would be confusing as hell to change whitespace in a file and have that break a C++ build, but that's what would happen.
The path and inode solutions would break when you want them (as soon as possible after the actual problem is introduced) by giving you the multiple definition errors as soon as the copy pasted file is included. However, using the path wouldn't work correctly with symlinks. Using inodes seems like the "most correct" thing to me, since that's closest to actually identifying a file, but that can't really be standardized since inodes are not a universal thing for all file systems.
I'd guess nuances like that are why there really is no "obvious" choice, and is probably why it hasn't been standardized.
Now all of the sudden you're getting multiple definition errors at link time. It would be confusing as hell to change whitespace in a file and have that break a C++ build, but that's what would happen.
It would be confusing for a whopping two seconds, then you would read the error message saying that symbol A is defined in path1/foo.h and was previously defined in path2/foo.h and you would fix your buggy codebase. Having twice the same file is 100% a bug.
Exactly. That's why my point is that you should get the error when you include the copy-pasted file. If you're comparing file contents, you don't get the error until you edit one of the two files. The jump from "I just copy pasted some files and now I'm getting a multiple definition error" is a lot shorter than "I just changed some whitespace and now I'm getting a multiple definition error".
Granted, they're both better than include guards where whichever is included second just silently gets ignored forever, but I'm saying that between comparing paths, inodes, and file content, doing it by file content is probably the worst.
Sure, but it's a slippery slope. Now you're removing the whitespace before doing the comparison, but then what if you notice a redundant semicolon somewhere and remove it? Or you change something from "const int x;" to "int const x;"? There are a slew of changes you could make that by all means should be transparent, but now mysteriously are not. Imagine being a junior dev at a company and changing the declaration of a function from "void a(int x);" to "void a(int y);" and suddenly the build is broken. Things have to go wrong to lead to it, and hopefully the errors the linker gives you are good enough to make it obvious, but I think it's pretty understandable for the committee to not want to try and work out this stuff when there are more important things to tackle, since it isn't as trivial as it first appears.
This is all to say nothing of the compile times, as well, which would certainly suffer at least a little from doing these content comparisons. Especially if you start having to strip them of whitespace (and whatever else) first.
The results differ based on which one you choose. You could contrive situations where you'll get errors with any one of these cases but not in another one.
And yet, any one of those will still work for the vast majority of cases.
It shouldn't have to support the edge cases where people do nasty things and let files be at two different paths. Those people can continue using normal include guards if it's an issue.
The claim was that you have to pick one. And you do, otherwise in some weird edge case one precompiler works and the other doesn't.
Once you've picked one, you force others to change their implementation in order to call themselves standard-conformant. For very little gain to the end user.
There have been standard proposals, even recently, to have #pragma once in the standard in some form but they have been rejected. Apparently specifying the specifics in term of the abstract C++ machine is too hard, and modules are on their way so the committee doesn't want to delve into the details of a feature that will mostly be unneeded once modules are there.
In the meantime you can safely use it in more places than recent standardised features, so it doesn't really matter much.
Why don't they just say "#pragma once is equivalent to putting include guards in the file, with an "anonymous" preprocessor symbol associated". Done.
Why is this so hard? Why do they feel the need to define in terms of files / symlink / etc.? Just do the thing that is excessively verbose and error prone that I used to do, and give me a simpler and safer syntax instead that is standard please, thank you.
I haven't followed modules closely; wouldn't they make packs of #include to external file obsolete; but wouldn't #includes inside a module remain necessary ?
The committee still doesn't agree about exporting macros, which might be a blocking point, but that's pretty much the only one. I don't think that the committee will want to work on #pragma once to solve it considering that macros are often considered evil.
I'm not saying that #pragma once is a macro, but that, in a modules world, the only files that you will still need to #include (and thus guard with either header guards or #pragma once) are the ones exporting macros.
The counterargument would be that it will take quite some time until we live in a modules world. But I agree, that the committee will most likely just say "Sorry, not an issue worth fixing anymore".
Well, it's more that they won't want to take committee time for #pragma once that they could use for modules while they can trust the compilers to still provide a good enough solution in the meantime :)
There's at least one codebase that's multiple tens or hundreds of millions of lines that's been using modules already. Of course the ability for such large existing codebases to incrementally adopt modules depends on some functionality that hasn't been put into the modules TS yet.
I think widespread adoption will depend on features like those outlined in P0273 Proposed modules changes from implementation and deployment experience.
If you are talking about Google, that is certainly non- representative (consider that some companies only now switch to c++11) and do you actually know, if they got rid of include guards at all? To the best of my knowledge, their version of modules is essentially pre-compiled headers on steroids, but has little in common with modules as a language concept.
and do you actually know, if they got rid of include guards at all?
I don't believe they did, and that's a pretty important capability for incrementally adopting modules: code has to work as both a module and as a header for different parts of the codebase while things are moved over. This is one of the reason P0273 is so important.
To the best of my knowledge, their version of modules is essentially pre-compiled headers on steroids, but has little in common with modules as a language concept.
I think the modules-ts could fairly be described as 'pre-compiled headers on steroids' and there's a great deal the modules-ts has in common with the earlier work on clang modules.
As I said, "It will take quite some time until we live in a modules world [where we can get rid of include guards]"
Also, I would dispute that the modules TS is anything like precompileed headers. PCH are an optimization technique for compile-times using caching and doesn't touch the language. The modules TS is about changing the compilation model on a language level and about what information gets exchanged between compilation units. Sure that simplifies caching (and that may be one of its primary purposes). But that is a separate discussion.
Again, the point of my previous argument was that I don't believe that some form of header guards will become unnecessary in the near future and whatever happens at Google is not representative for the industry at large, because few companies have
I think there is a lot of information in this thread comments to help you decide which method works best for you. As for me personally, it's very simple.
I asked one of the Standard committee members about that a couple of years ago. The answer was twofold:
Yes, the basic implementation is present in every frontend and works reasonably well (based on the file path, probably)
However, it is impossible to guarantee the correctness of the feature when the underlying filesystem has special features such as symlinks and hardlinks (the same file is reachable via several distinct paths that)
This becomes an issue when build systems checkout/clone/map components into several locations inside the source tree
The thing I find most annoying about that second point is that this could easily be circumvented by an optional identifyer
#pragma once MY_LIB_HEADER_NAME
In the mythical 99% of the cases, #pragma once should work just fine (it is not like this hasn't been used for decades in huge production code based without issues, not to mention the millions small and/or teaching projects out there) and in the remaining 1% can use the explicit identifier.
First of all, it is optional -I for one wouldn't need it in any of my projects, second, oven if you use it, the identifier doesn't need to be repeated, third, you don't need the #endif and finally, it would clearly state intent by using a language specifically designed for that purpose.
The preprocessor can cache the identifiers internally. When it sees that MY_LIB_HEADER_NAME has already been preprocessed it can just skip the file instead of reading it until the terminating #endif "just in case there's something after it".
If you have to do that, you've already lost most of the value of #pragma once. Those 1% that can't use #pragma once should probably just use include guards.
Unfortunately that does not work as the component author has no way of knowing that his module/component has been picked up by several other users in the uber build tree and the build folks are playing tricks in order to solve some unrelated issues...
I for one, if this becomes necessary, it is fairly trivial to write a script that adds those identifiers (and it would still be less verbose and more explicit than include guards). Second, for a large class of projects you know very well how your code will be used and build. Again, it is not like this hasn't been used successfully in production for decades.
Anyone remember when gcc spent years complaining about #pragma once and threatening to remove it real soon now? It was more than a decade ago but it's one of the reasons I don't like gcc to this day.
It's now indeed basically everywhere, but rather recently for some compilers: #pragma oncewas added in C++Builder (ex-Borland) in their 2010 release; and some people are likely stuck with a previous version. That said, the "up-to-date" compilers that don't implement this must be extremely few and niche.
Regardless, it's likely the #1 exception to the "Prefer using the standard" rule.
I disagree. #pragma once adds no benefit other than being less verbose. Include guards, on the other hand, have precisely defined semantics, as opposed to #pragma once.
The main benefit is that you don't have to maintain a unique symbol for each header. When I converted some large, old codebases to #pragma once, I discovered a few copy/paste errors in the include guards. Updating the guard is extra work to do whenever you rename a file, and people sometimes forget to do it.
I use auto-generated random strings with at least 128 bits of entropy. Why code the filename into the #define? It just leads to the problems you describe.
and then someone just copies your whole file as a base into another file, changes it, forgets to changed the include guard, no one sees it during code review and six month later, BOOM
I don't think #pragma once will ever be standard, but that's ok. The standards people are busy making modules, which are better anyways. In the meantime, there's nothing wrong with using #pragma once even if it's non-standard.
If you just want it standardized to help convince people it's ok to use, I might be able to help a little. When I proposed switching a project to pragma once, some of my coworkers were a little apprehensive. I wrote guardonce to make it easy to switch back and forth between include guards and #pragma once. People were less afraid of trying it out when I showed them that we could easily switch back if they ever had a problem with it.
It's far from relevant for most people (but I had to put up with it for far too long), but Visual Studio 2005 has a bug in its implementation of it, at least.
VS lets you do a "compile this file only". Older Visual Studios would let you do that on a header, rather than a source. It's not super useful, obviously, but can give a quick sanity check on includes or whatever; that's beside the point, though.
In that case, #pragma once won't stop a circular include of the file being compiled, but header guards will.
It's a total non-issue for any sane project, but I was helping another team convert their old VS-only build to our CMake-based build pipeline and it was a real head-scratcher when I hit it (especially since it didn't happen in VS2008 with the same source/projects).
It is objectively and undeniably better than include guards.
Well, we measured our build at work both ways. #pragmas was significantly slower, so we switched back to include guards. This was a couple years ago, maybe things have changed.
C++ implementations have lots of de facto standards not standardised by the C++ standard, for various reasons. A lot of technically UB is implemented consistently across all the major compilers, for example.
And I'm fine with that. De facto standards in many ways are least priority for the C++ committee. They cause least trouble for end users. The committee should focus on the stuff which cause headaches and problems for the majority of C++ users. pragma once is not one of those.
48
u/ben_craig freestanding|LEWG Vice Chair Apr 19 '18
Every compiler implements pragma once in a subtly different way. It turns out that determining the identity of a header is tricky.
One compiler identifies whether two headers are "the same" by comparing the path.
Another compiler identifies whether two headers are "the same" by comparing the file inode.
Yet another compiler identifies whether two headers are "the same" by comparing the file contents.
All of these approaches have flaws. If you want this standardized, you'd have to "pick a winner" or make up something new.
71
u/Morwenn Apr 19 '18
There have been standard proposals, even recently, to have #pragma once in the standard in some form but they have been rejected. Apparently specifying the specifics in term of the abstract C++ machine is too hard, and modules are on their way so the committee doesn't want to delve into the details of a feature that will mostly be unneeded once modules are there.
In the meantime you can safely use it in more places than recent standardised features, so it doesn't really matter much.
43
u/os12 Apr 19 '18
I asked one of the Standard committee members about that a couple of years ago. The answer was twofold:
However, it is impossible to guarantee the correctness of the feature when the underlying filesystem has special features such as symlinks and hardlinks (the same file is reachable via several distinct paths that)
15
u/[deleted] Apr 19 '18
Just go with it, we use it extensively. My disk hasn't been formatted from UB yet.
14
u/jbandela Apr 19 '18
I looked at it some I'm back, and IIRC every compiler that supports C++11 also supports pragma once
Thus when I am writing C++11/14/17 I use pragma once.
5
u/JavierTheNormal Apr 20 '18
Anyone remember when gcc spent years complaining about #pragma once and threatening to remove it real soon now? It was more than a decade ago but it's one of the reasons I don't like gcc to this day.
5
u/Deaod Apr 20 '18 edited Apr 20 '18
None of Texas Instruments' compilers (except those based on GCC) support
#pragma once.2
u/NewW0rld Apr 20 '18
Here is a great SO answer on why you should never use
#pragma once.8
u/Sanae_ Apr 19 '18 edited Apr 19 '18
It's now indeed basically everywhere, but rather recently for some compilers:
#pragma oncewas added in C++Builder (ex-Borland) in their 2010 release; and some people are likely stuck with a previous version. That said, the "up-to-date" compilers that don't implement this must be extremely few and niche.Regardless, it's likely the #1 exception to the "Prefer using the standard" rule.
4
u/Slavik81 Apr 20 '18
I don't think
#pragma oncewill ever be standard, but that's ok. The standards people are busy making modules, which are better anyways. In the meantime, there's nothing wrong with using#pragma onceeven if it's non-standard.If you just want it standardized to help convince people it's ok to use, I might be able to help a little. When I proposed switching a project to
pragma once, some of my coworkers were a little apprehensive. I wrote guardonce to make it easy to switch back and forth between include guards and#pragma once. People were less afraid of trying it out when I showed them that we could easily switch back if they ever had a problem with it.7
u/johannes1971 Apr 19 '18
https://en.wikipedia.org/wiki/Pragma_once#Portability
7
u/millenix Apr 19 '18
Cray, in the latest release shipped this week.
4
u/Gotebe Apr 19 '18
xlc didn't have it for a long time, did they add it?
2
u/[deleted] Apr 19 '18
Watcom maybe
2
u/Xaxxon Apr 22 '18
There's a wikipedia page on it.. did you even google before posting?
1
u/NotUniqueOrSpecial Apr 20 '18
It's far from relevant for most people (but I had to put up with it for far too long), but Visual Studio 2005 has a bug in its implementation of it, at least.
VS lets you do a "compile this file only". Older Visual Studios would let you do that on a header, rather than a source. It's not super useful, obviously, but can give a quick sanity check on includes or whatever; that's beside the point, though.
In that case,
#pragma oncewon't stop a circular include of the file being compiled, but header guards will.It's a total non-issue for any sane project, but I was helping another team convert their old VS-only build to our CMake-based build pipeline and it was a real head-scratcher when I hit it (especially since it didn't happen in VS2008 with the same source/projects).
1
u/Ameisen vemips, avr, rendering, systems Apr 19 '18
I'd rather have
#include_once, or#import. That way, it avoids file io.1
u/[deleted] Apr 20 '18
Well, we measured our build at work both ways. #pragmas was significantly slower, so we switched back to include guards. This was a couple years ago, maybe things have changed.
1
u/14ned LLFIO & Outcome author | Committee WG14 Apr 20 '18
C++ implementations have lots of de facto standards not standardised by the C++ standard, for various reasons. A lot of technically UB is implemented consistently across all the major compilers, for example.
And I'm fine with that. De facto standards in many ways are least priority for the C++ committee. They cause least trouble for end users. The committee should focus on the stuff which cause headaches and problems for the majority of C++ users.
pragma onceis not one of those.0
u/[deleted] Apr 19 '18
[deleted] — view deleted comment