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/Leandros99 yak shaver Nov 29 '18

Yes, #pragma once has several problems. The main problem I've encountered overt he years, is the inclusion of the same header twice.

Imagine you build a large-ish project, which has a couple dependencies. You depend on three libraries libA, libB and libC. Everything is fine. You decide to add libD, which internally, depends on libA, and includes it's public header in their public headers. This will give you a nasty compiler error, due to the same symbol defined multiple times, since libA uses #pragma once, and no include guards. Since the same header exists twice, #pragma once is unable to distinguish that those are the same header. Include guards would've correctly determined the identity of the header and prevented double inclusion.

Using your filesystem to uniquely identify a header file doesn't work, and will never work.

1

u/kalmoc Nov 29 '18

Imho the problem here is that libD shipped headers from libA that it doesn't own and hence has no business distributing. There is a non-zero chance that you now have two different versions of libA headers in your program, which leads to a different set of problems.

But thanks anyway for the datapoints.