[Development] Using '#pragma once' instead of include guards?

Alejandro Exojo suy at badopi.org
Tue Oct 11 21:31:36 CEST 2022


On Mon, Oct 10, 2022, at 12:11 PM, Hasselmann Mathias wrote:
> I am surprised by the question: "It's non-standard and it's behavior is 
> undefined" actually should be enough to avoid such feature.

I suggest that you don't look at the implementation of things like Q_OFFSETOF, then. ;-)

// This macro can be used to calculate member offsets for types with a non standard layout.
// It uses the fact that offsetof() is allowed to support those types since C++17 as an optional
// feature. All our compilers do support this, but some issue a warning, so we wrap the offsetof()
// call in a macro that disables the compiler warning.

Well, it's just one example that I could quickly think of, but I think it's not uncalled for that a project just relies on the implementation of the set of supported compilers doing the same, or something equivalent enough. It's hard to tell how widespread is the use of #pragma once, but note that in a simple Reddit poll done a few months ago, the pragma got 65% of the votes, almost twice as include guards:

https://www.reddit.com/r/cpp/comments/rxb6r2/include_guards_or_pragma_once/

> Actually if a reliable implementation of "#pragma once" would be 
> possible, that feature would have been included in the C++ standard for 
> a long time already, wouldn't it?

Same example. The comment on Q_OFFSETOF hints that C++17 seems to allow for optional implementations to go beyond what the standard specifies. Why is not standardized then? I think the same could be said about this pragma. What it does is conceptually very simple, and if it only can hurt on very corner cases, then it's a matter of weighting the tradeoffs.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/development/attachments/20221011/5858e96e/attachment.htm>


More information about the Development mailing list