Modern C and C++ compilers support the non-standard #pragma once
, preprocessor directive, which serve a similar purpose to the classic header guards:
#ifndef hopefully_unique_identifier_that_doesnt_hurt_the_code
#define hopefully_unique_identifier_that_doesnt_hurt_the_code
// some code here
#endif
One problem, I'm aware of, with the classic approach is that once you've included a header, you have to #undef
the header guard macro to include it again (doing so, to me, is a major code-smell, but that's beside the point here). The same problem arises with the #pragma once
approach, but without the possibility of allowing the header to be included more than once.
Another problem with the classic-approach is that you may, accidentally, define the same macro in unrelated places, thus either not including the header as expected or doing some other nasty stuff, that I can't imagine. This is reasonably easy to avoid in practice, by keeping to certain conventions such as basing the macros to UUID-like objects (i.e. random strings) or (the less optimal approach), basing them on the name of the file, they are defined in.
I have only rarely experienced any of these, potential problems, in real life, so I don't really consider them to be major problems.
The only potential real life problem I can think of with #pragma once
, is that it's not a standard thing -- you're relying on something that may not be available everywhere, even if it is present, in practice, everywhere (*).
So, what potential problems exist with #pragma once
, besides the ones I've already mentioned? Am I having too much faith in having it available, in practice, everywhere?
(*) Some minor compiler that only a handful of people use, excluded.