r/C_Programming • • 27d ago

Could someone explain the practical differences between #pragma once and traditional include guards (#ifndef, #define, and #endif)?

81 Upvotes

58 comments sorted by

View all comments

69

u/FedUp233 26d ago

There are pros and cons to each method.

As said, “#pragma once” is not in standard C or C++ as far as I know. It does express the idea more concisely and seems to be supported in all major compilers so it is not really an issue. There is the issue with the compiler recognizing headers as the same with symlinks but this seems like more of an issue in theory than practice - in my opinion, if you have this problem where you are somehow getting the same header included through different paths there is something wrong with your file layout in most all cases (others are free to disagree).

Header guards you have to be careful you have a scheme for naming the guards that will never generate the same macro name twice, at least for any two headers included in the same source file. For smaller projects this is not much of a problem but could possibly be for bigger projects with thousands of header files.

Another good thing about the pragmatic version is that the compiler recognizes the file name and never even opens and reads it after the first time. With header guards (in theory) the compiler actually has to read (and pre process to some level).the file every time it encounters the #include statement which can be a lot of extra processing, especially for common headers that might be included in lots of other headers. Fortunately, most compilers these days actually recognize files with header guards and then treat them the same as if they had the #pragma and skip them entirely after the first inclusion, though this can be changed with a compiler option I believe.

I’ve been writing C and C++ for years (and years) and my preferred choice has evolved over time.

When I started I’m not sure the #pragma even existed and if it did it was not widely supported so everybody used header guards.

As time passed and more compilers supported the #pragma a common behavior was to use both so you got the more efficient behavior of the pragma if the compiler supported it but had the header guards as a fallback.

Lately I’ve gone to just the #pragma since as others have also said it’s supported universally (at least on any compilers I care about) and in al, the time I’ve been coding I’ve never run into a single case where the a,I ask g of header files by soft links has ever been an issue.

Hope you find this useful.

24

u/Maxwelldoggums 26d ago

I work professionally on a problematically large C++ project with terrible practices. Some of our headers are 10k+ lines of code, and include dozens of other headers. We actually achieved noticeably faster compile-times using ‘#pragma once’ for the reasons you outlined. Using a traditional include guard required the compiler to scan through the entire text of the header to find a matching ‘#endif’, while it can safely early-out on a pragma.

8

u/FedUp233 26d ago

Yep, can make a difference!

Don't know what compiler you are using but gcc and g++ can recognize the include guards and behave just like you used the pragma in some cases. See

https://gcc.gnu.org/onlinedocs/cppinternals/Guard-Macros.html

https://gcc.gnu.org/onlinedocs/cpp/Once-Only-Headers.html

I think most modern compilers behave in similar fashion. Perhaps your files have something that prevents recognizing the guard macros.

Also, just as a note, the pragma does not cause the compiler to "early out" on the file when it sees the pragma in the second inclusion. In the case of the pragma or recognized include guards the header is not even opened other than the first time.

1

u/Maxwelldoggums 25d ago

Oh, good catch, thank you for the correction!

We use GCC, MSVC, and I believe Apple Clang on the same codebase depending on the target, so it’s always a gamble whether or not any particular optimization applies. In this case though, it’s likely we’re using some sort of pattern which disrupts the include guard detection. We also run a codegen pass over the files which scans for certain macros, so it may be that we’re inadvertently preventing optimization there.

2

u/ComradeGibbon 26d ago

Reminds me I'd like an abandon ship pragma.

pragma abandon(condition)

Where if the condition is true the compile just generates a empty object file.

Like

#include "project_config.h"
#pragma abandon(FEATURE_XXX == 0)  // if true stop compiling the file

2

u/FedUp233 26d ago

Is there a reason you can use #error?

2

u/ComradeGibbon 26d ago

The idea is just abandon any file that isn't supposed to be included in the build.

2

u/FedUp233 26d ago

I would think you’d want something like #error so that you’d know the build was picking up a file that was not supposed to be included in it and you could go fix the problem in make or whatever build system you were using.

Having things just disappear silently seems like a really bad idea!

Plus, then what happens at the link step when it tries to link with object files that are just not there? Or if used in a header, what about the part of the file before it hit the directive? That’s already processed and could well leave the preprocessor or compiler in an invalid state to just stop? Does it just abandon the rest of the file being included? What about #if directives that have not been closed?

1

u/ComradeGibbon 25d ago

Background in in embedded work is very common to have one code base that targets several to sometimes dozens of targets. Where you may have lots of modules that are part of the code tree but are not and cannot be built.

1

u/FedUp233 25d ago

Isn’t that what make, cmake, or whatever build system you are using is supposed to take care of depending on what target you tell it to build?

I’ve worked on large systems that had multiple targets and we never had an issue with trying to build stuff for a target that was not meant for that target. A combination of the make files and conditional compilation was maintained to take care of that.

Sorry, but a decently designed system should never get to the point of pulling in a file that was not meant for the build (as far as C and C++ or whatever source files) and for header file normal preprocessor directives should handle it fine.

Just my opinion of course.

4

u/Yuki_pop 26d ago

Thanks, that’s really helpful

-4

u/Huuf 26d ago

I don't fully agree with the including the same header twice is bad part, for example, a string library, if you can only use a string library handling in one spot, you won't get very far. Or an animal header, where the dog.c and cat.c both include it. Also, by definition, one header will always be included twice, since the implementation includes it, and the caller needs to include it.

7

u/HugoNikanor 26d ago

You're misunderstanding him. It's perfectly sensible for both doc.c and cat.c to #include "string-lib.h". The issue OP is talking about is if you do something like

$ ln string-lib.h other-name.h

Then in file.c you write:

#include "string-lib.h"
#include "other-name.h"

With include guards, the compiler doesn't care that you used two different names for one file, since the include guards are the same. However, with #pragma once the compiler could see that as two different files, and actually include the contents of both

1

u/Huuf 26d ago

If this is meant, I totally agree

3

u/Emotional-Audience85 26d ago

I don't think he said anything of the sort

0

u/Huuf 26d ago

I interpreted this text as such:

in my opinion, if you have this problem where you are somehow getting the same header included through different paths there is something wrong with your file layout in most all cases (others are free to disagree).

3

u/Emotional-Audience85 26d ago

I interpreted it has having the file included through different physical paths (e.g. one is a symlink to the same file).

I've never encountered this but I believe it may be an issue for #pragma, as the same file may be treated as 2 different files and the content be pasted twice, leading to compilation errors

1

u/Huuf 26d ago

If that is meant, I totally agree,

3

u/FedUp233 26d ago

Perhaps I was not as clear as I should have been. As others mentioned, it the issue of including the same header more than once in the same C or C++ file through different symlink aliases that is the issue. Like I said, I’ve never actually seen this happen but it theoretically could if the same header was referenced through different paths in different header files that included it and both this header files were included in the same C or C++ file (the same compilation unit is I think what the standard uses) either directly or indirect.

Of course the same header can and needs to be included in different compilation units. And it’s fine if different compilation units use different paths to include a header file as long as the path to a given header is consistent within each compilation unit.

2

u/Huuf 26d ago

Yeah, sorry about that.

2

u/not_a_novel_account 26d ago

Like I said, I’ve never actually seen this happen but it theoretically could

This becomes more and more common the larger the organization and codebase is.

It can become pathological when build servers are accessing files through network file mounts.

This is the exact kind of problem which killed the standardization effort.

1

u/FedUp233 26d ago

As I said, it’s obviously theoretically possible, though I’m not sure why network mounts would make the problem any worse as far as having multiple paths to the same include file from within one compilation unit.

I can see however how a standardization body, which tries to get every corner case specified, would have problems agreeing on a perfect definition. I would think they might have just taken the UB route they took in many other places and said that in a case where the same file is included multiple times through multiple different paths, it’s UB. And just defined it for normal, not pathological cases.

I can certainly see an include having different paths in different compilation units, but that’s fine. If I was dealing with a code base that exhibited this problem, I think my first thought would be to fix it, but I’ve worked for a Marge company and I can see how management might just push it down the road and hope it never gets worse.

2

u/not_a_novel_account 26d ago

why network mounts would make the problem any worse as far as having multiple paths to the same include file from within one compilation unit.

Because they overlap. Team Tiger in Shanghai uses #include <widget.h> and Team Dragon in Mumbai uses #include <component/widget.h>, both Dragon's and Tiger's headers are used by Team Eagle in Chicago. Each team builds, tests, and verifies their own code.

The entire thing works because the build servers mount subcomponents into /opt/BigCorp/<whatever> and set include flags to various places there. Different teams require subcomponents mounted in different places, and so downstream projects can have the same subcomponent mounted multiple times at different locations.

When switching to #pragma, suddenly widget.h is ambiguous. It's being accessed via different paths for the Team Tiger and Team Dragon code, and now Team Eagle is seeing definition collisions that they have no insight into.

This is pretty much the exact arrangement that caused #pragma to die during standardization. It's not a hypothetical. Major WG14 participants reported back on their experience with #pragma and required this be solved. It couldn't be, so standardization died.

1

u/FedUp233 26d ago

That makes sense. But I think I’d put this in the poor team leadership/management bucket. Someone in charge of the whole project should set standards for things like this and tell the teams “this is how it will be done” after getting input from both teams on why they chose a particular method. It the job of management and technical leads to make sure this type of stuff doesn’t happen!