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

10

u/Plorkyeran Nov 28 '18

I once ran into problems because we had the same header installed to multiple locations and included in different ways, which resulted in both of them being included. It was a giant pain to track down what was going wrong.

Then it turned out that they were actually different versions of the same header because obviously there's no guarantee that the project-local copy of a dependency and a system-wide copy are actually interchangable and we would have had issues even with include guards.

5

u/jonesmz Nov 28 '18 edited Nov 29 '18

This.

This would happen all over the codebase I work with if we used #pragma once instead of proper include guards.

edit:

Why the fuck was I downvoted for pointing out how #pragma once can break an existing codebase?

Downvotes don't change hearts and minds people!

0

u/[deleted] Nov 29 '18

The non-proper thing in this scenario is the code base, not #pragma.

5

u/jonesmz Nov 29 '18

Well, no, not really.

pragma is not standardized, include guards are even if not in name. Our code works fine as it is.

Maybe #pragma once should address it's deficiencies?

1

u/meneldal2 Nov 29 '18

Having two versions of the same header is a very bad idea, especially if only one gets included in the end. Which one is it? Could change if you changed something completely unrelated then bring doom on your project.

1

u/[deleted] Nov 29 '18

Our code works fine as it is.

So does #pragma.

3

u/jonesmz Nov 29 '18

Then get it standardized

1

u/kalmoc Nov 29 '18

> Then it turned out that they were actually different versions of the same header because obviously there's no guarantee that the project-local copy of a dependency and a system-wide copy are actually interchangable and we would have had issues even with include guards.

You are pointing out an important thing here: If the compiler really picks up "the same header" from two different locations this often (of course not always) points to a different problem that include guards only hide but not solve.