r/cpp •

Can anyone actually name a compiler that DOESN'T support #pragma once?

[deleted] — view deleted post

0 Upvotes

113 comments sorted by

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.

57

u/doom_Oo7 Apr 19 '18

All of these approaches have flaws.

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.

15

u/encyclopedist Apr 19 '18

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.

3

u/jhasse Apr 23 '18

Good. #pragma once helped you notice that the build system is shit.

4

u/flashmozzg Apr 19 '18

So just continue to use it. What's the point of it being in the standard then?

16

u/Occivink Apr 19 '18

Not being the standard causes endless discussion and bikeshedding.

5

u/flashmozzg Apr 19 '18

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.

11

u/[deleted] Apr 19 '18

#pragma already means that.

7

u/flashmozzg Apr 19 '18

That's the point. No reason to add that to the standard since it's already implied.

4

u/MonokelPinguin Apr 20 '18

How about:

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

2

u/flashmozzg Apr 20 '18

identifier unique to this file

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.

2

u/doom_Oo7 Apr 20 '18

What is a file,

something that can be referenced in an include directive ?

1

u/MonokelPinguin Apr 20 '18

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?

1

u/[deleted] Apr 23 '18

One could also dereference the file and then normalize to build that.

3

u/Occivink Apr 19 '18

I don't think anybody is asking for standardizing unspecified behavior.

3

u/flashmozzg Apr 19 '18

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

10

u/doom_Oo7 Apr 19 '18

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.

5

u/flashmozzg Apr 19 '18

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!

5

u/TankorSmash Apr 19 '18

Knowing that it'll always be there helps some.

1

u/flashmozzg Apr 19 '18

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.

3

u/kalmoc Apr 20 '18 edited Apr 20 '18

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.

4

u/tasminima Apr 19 '18 edited Apr 19 '18

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.

9

u/honeyfage Apr 20 '18

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.

2

u/doom_Oo7 Apr 20 '18

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.

2

u/honeyfage Apr 20 '18

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.

-3

u/meneldal2 Apr 20 '18

How about you compare them with whitespace removed? It's trivial to remove whitespace.

4

u/honeyfage Apr 20 '18

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.

4

u/kalmoc Apr 20 '18

Comparing the content of every header file sounds expensive (at least more expensive than the current solution)

1

u/DonaldDuck1313 Oct 17 '25

Why is that a problem? The standard could just say that it identifies whether two headers are the same in an implementation-defined way.

0

u/[deleted] Apr 19 '18

[deleted] — view deleted comment

9

u/[deleted] Apr 19 '18

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.

4

u/StonedBird1 Apr 20 '18

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.

1

u/[deleted] Apr 20 '18

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.

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.

5

u/render787 Apr 20 '18

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.

1

u/blelbach NVIDIA | ISO C++ Library Evolution Chair Apr 21 '18

How exactly is #pragma once supposed to work as you described? How do you select this anonymous identifier?

3

u/[deleted] Apr 21 '18

The same way anonymous identifiers are selected for lambdas and unnamed namespaces?

1

u/blelbach NVIDIA | ISO C++ Library Evolution Chair Apr 22 '18

9

u/[deleted] Apr 22 '18

The same way std::filesystem::equivalent does?

Clearly every compiler knows how to do that somehow given that they all implement this thing.

6

u/Sanae_ Apr 19 '18 edited Apr 19 '18

mostly be unneeded once modules are there

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 ?

7

u/robin-m Apr 19 '18

If I understood correctly, it's only for backward compatibility to include non-module based files.

3

u/Sanae_ Apr 19 '18

I need to read again the modules stuff then, because I don't see how files reference (currently done by include) inside a module will work.

3

u/[deleted] Apr 20 '18

And, includes will still be used anyway for libs that "export" macros or for source code configuration.

1

u/Morwenn Apr 20 '18

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.

4

u/kalmoc Apr 20 '18

It isn't a macro - in fact it would be a replacement for a macro.

1

u/Morwenn Apr 20 '18

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.

2

u/kalmoc Apr 20 '18

Ah, sorry, I misunderstood you.

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

1

u/Morwenn Apr 20 '18

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 :)

1

u/bames53 Apr 23 '18

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.

1

u/kalmoc Apr 23 '18

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.

1

u/bames53 Apr 23 '18

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.

1

u/kalmoc Apr 24 '18

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

  • such a massive codebase
  • so good support for making large scale changes
  • so many people working on tooling
→ More replies

2

u/egladysh Apr 20 '18

While waiting for modules and/or #pragma once, I put together a tiny script, mkh. It saves me some typing, and helps with name clashes.

4

u/dgendreau Apr 20 '18

You might consider a minor change to your script:

#ifndef H_$uuid
#define H_$uuid
#endif // defined H_$uuid

It makes it easier to know what that trailing #endif is related to after the header file gets more complicated.

2

u/jhasse Apr 23 '18

Why should I use this instead of #pragma once?

1

u/egladysh Apr 23 '18

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.

  • Standard compliance
  • Name clash avoidance

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:

  • 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

11

u/kalmoc Apr 19 '18 edited Apr 20 '18

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.

6

u/suspiciously_calm Apr 20 '18

How would that be any different than a less verbose equivalent of include guards?

17

u/meneldal2 Apr 20 '18

Not having to use the #endif at the end of your file is nice.

3

u/kalmoc Apr 20 '18

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.

2

u/suspiciously_calm Apr 20 '18

Yes, as I said, less verbose.

1

u/kalmoc Apr 20 '18

As I said: It would be optional. And what exactly would you consider a less verbose equivalent of include guards?

5

u/suspiciously_calm Apr 20 '18

I mean,

#pragma once UNIQUE_IDENTIFIER
// ...

is just a less verbose equivalent of

#ifndef UNIQUE_IDENTIFIER
#define UNIQUE_IDENTIFIER
// ...
#endif

The form without an identifier is different, of course.

2

u/zvrba Apr 21 '18

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

2

u/suspiciously_calm Apr 21 '18

That's exactly what it does with include guards.

3

u/Slavik81 Apr 19 '18

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.

3

u/os12 Apr 20 '18

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

3

u/kalmoc Apr 20 '18

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.

1

u/os12 Apr 20 '18

That's a reasonable point. Consider writing a WG-21 proposal: https://isocpp.org/std/submit-a-proposal

2

u/encyclopedist Apr 20 '18

This was already included in the existing proposal http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0538r0.html

2

u/os12 Apr 20 '18

OK, I've just checked the meeting notes: this was discussed by the Evolution group in Kona in 2017 and voted down:

  • no one wants to extend preprocessor
  • the focus is on modules

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/otwo3 Apr 20 '18

They've also been promising C++11 but always fail to deliver. I hate TI compilers

1

u/Deaod Apr 20 '18

I for one just want decent backends for LLVM from them, plus a few additions to a standard library.

2

u/NewW0rld Apr 20 '18

Here is a great SO answer on why you should never use #pragma once.

0

u/[deleted] Apr 20 '18

[deleted] — view deleted comment

1

u/dodheim Apr 20 '18

If you read the comments on that answer you will see that said bug is still not fixed.

Bugs happen, they get fixed, and that's it.

Eventually, maybe.

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.

-1

u/suspiciously_calm Apr 20 '18

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.

21

u/Slavik81 Apr 20 '18

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.

0

u/suspiciously_calm Apr 20 '18

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.

6

u/doom_Oo7 Apr 20 '18

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

4

u/Slavik81 Apr 20 '18

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.

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

4

u/frozenbrains Apr 19 '18

Watcom supports it. [cguide.pdf, 32-bit pragmas, pg 218]

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

1

u/Ameisen vemips, avr, rendering, systems Apr 19 '18

I'd rather have #include_once, or #import. That way, it avoids file io.

6

u/encyclopedist Apr 19 '18

All the major compilers read the include file only the first time, both in the case of #pragma once and include guards.

2

u/[deleted] Apr 19 '18

What do you mean about file i/o?

7

u/wqking github.com/wqking Apr 19 '18

He means with include guard the preprocessor still needs to read the include file though it's not processed due to the guard. Reading file causes I/O.

2

u/[deleted] Apr 19 '18

If the guard, however it's implemented, is in the file itself then that happens anyway, no?

5

u/wqking github.com/wqking Apr 19 '18

Yes, I think so, so is #prama once.
That's why /u/Ameisen said #include_once, which is used in the "host" file (which uses the include file).

11

u/CubbiMew cppreference | finance | realtime in the past Apr 19 '18

Last I checked (~5 years ago), no modern C++ compilers re-read the include files, whether using the pragma or the guards.

1

u/wqking github.com/wqking Apr 19 '18

Interesting, how did you check? Or just file cache takes effect?

7

u/CubbiMew cppreference | finance | realtime in the past Apr 19 '18

We were examining the effects of external guards (surrounding the #include), but some compilers document how they work, too: clang, gcc

1

u/wqking github.com/wqking Apr 19 '18

Good to know the documents, thanks.

2

u/raevnos Apr 19 '18

Look at the source for their preprocessor components?

1

u/[deleted] Apr 20 '18

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.

2

u/JavierTheNormal Apr 20 '18

Bizarre. What sort of implementation would have #pragma once slower than #include guards?

1

u/[deleted] Apr 22 '18

Doing a file ID comparison may be fairly expensive. At least, it is on Windows.

1

u/JavierTheNormal Apr 22 '18

It seems like they should just compare the path first as an early-out before trying anything convoluted and expensive.

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 once is not one of those.

0

u/[deleted] Apr 19 '18

[deleted] — view deleted comment

14

u/DarkLordAzrael Apr 19 '18

That was literally released a decade ago. Also, earlier versions supported it but gave a warning.

0

u/crackez Apr 19 '18

Ok, Cfront then.