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

Paul Colby qt at colby.id.au
Mon Oct 10 22:38:10 CEST 2022


Also worth considering
https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rs-guards

SF.8:

> Note Some implementations offer vendor extensions like #pragma once
> as alternative to include guards. It is not standard and it is not
portable.
> It injects the hosting machine’s filesystem semantics into your program,
> in addition to locking you down to a vendor. Our recommendation is to
write
> in ISO C++: See rule P.2.

Cheers.

On Tue, 11 Oct 2022, 7:23 am Henry Skoglund, <henry at tungware.se> wrote:

> On 2022-10-10 21:27, Thiago Macieira wrote:
> > ...
> > This situation is annoying either way. With include guards, you will get
> a
> > working build, but you may spend some time trying to figure out why the
> changes
> > you're making to the headers aren't taking effect. With the pragma, you
> get
> > hard build errors due to redefined types, probably with both paths so
> you'd
> > notice easily that there are two copies.
> >
> > The problem I have with switching to #pragma once is for whom the problem
> > happens and who gets to fix it. Most people who build Qt from source are
> not
> > developing or modifying it; they're simply building for use in their own
> > content. So if the problem of incorrect include paths happens with
> > preprocessor guards, most likely they will not see any ill effect
> because both
> > copies of headers are the same. But if those headers use #pragma once,
> those
> > people will get build errors despite the file contents being identical,
> because
> > they are different files.
>
> Hi, this kind of reminds me of detecting violations of ODR but instead
> of objects it's about .h files. And #pragma once can then be seen as the
> weaker sibling of the include guard mechanism, i.e. not as efficient as
> detecting multiple instances of the same .h file.
> But perhaps there could be use of #pragma once anyway, as a way to
> detect those duplicate files? Say something like this at the top of an
> .h file:
>
> #pragma once
> #if defined QGLOBAL_H
> #error "Multiple instances of qglobal.h detected"
> #endif
> #define QGLOBAL_H
> ...
>
> Rgrds Henry
>
> _______________________________________________
> Development mailing list
> Development at qt-project.org
> https://lists.qt-project.org/listinfo/development
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/development/attachments/20221011/71e013ba/attachment.htm>


More information about the Development mailing list