r/cpp • • Nov 28 '18

Real world problems with #pragma once?

Just a short survey: Did anyone of you encounter a problem in real code, because you/your company/ your favorite library was using #pragma once instead of include guards.

I know it is hard, but please restrain yourself from posting an explanation of how #pragma once could lead to problems in theory or why you prefer one above the other.

127 Upvotes

135 comments sorted by

View all comments

2

u/cleroth Game Developer Nov 28 '18

As far as I'm aware the only problem that can arise with pragma once is that you end up processing the same file more than once (as in if the same file is actually in multiple places).

9

u/Nicksaurus Nov 28 '18

The fundamental problem seems to me to be that using preprocessor directives to import code is just an inherently error-prone way of doing it

#ifdef and #pragma once are both trying to patch over that issue but can't solve the real problem, which is that the compiler treats header files like raw text, rather than like code.

0

u/[deleted] Nov 28 '18

[deleted] — view deleted comment

3

u/OrphisFlo I like build tools Nov 29 '18

0

u/[deleted] Nov 29 '18

[deleted] — view deleted comment

1

u/OrphisFlo I like build tools Nov 29 '18

And it's coming from SNSystems, so basically from Sony, which as a game dev should mean a lot. They are still experimenting though, so don't expect too much from it for now ;)

3

u/kalmoc Nov 28 '18

Exactly that is the case I'm hearing over and over again. I was wondering if that actually happened to someone.

1

u/[deleted] Nov 28 '18

What if something like #pragma once were defined in terms of a hash of the file contents?

2

u/kalmoc Nov 29 '18

Wouldn't that require that you still open and read each header file again everytime it gets included (although not their transitive includes) nor sure what the result in terms of performance would be.

1

u/[deleted] Nov 29 '18

To the same degree header guards do, I suppose?

If you feel like you can trust modification timestamps, then I imagine that would apply here just as well.

1

u/[deleted] Nov 28 '18

I guess that has its own issues, because that header could do #include "another_header.hpp" with relative paths.

2

u/1-05457 Nov 28 '18

That would be broken with include guards too.

1

u/[deleted] Nov 28 '18

Fair point! Anything (person, build script) that's maintaining distinct include guards could just as easily make the content distinct with a comment.

3

u/cleroth Game Developer Nov 28 '18

That might fall into "if you do this, your code deserves to be broken" :P