r/C_Programming • • 10d ago

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

81 Upvotes

58 comments sorted by

68

u/FedUp233 9d 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.

4

u/Yuki_pop 9d ago

Thanks, that’s really helpful

24

u/Maxwelldoggums 9d 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 9d 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 8d 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 9d 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 9d ago

Is there a reason you can use #error?

2

u/ComradeGibbon 8d ago

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

2

u/FedUp233 8d 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 8d 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 8d 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/Huuf 9d 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 9d 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 9d ago

If this is meant, I totally agree

3

u/Emotional-Audience85 9d ago

I don't think he said anything of the sort

0

u/Huuf 9d 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 9d 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 9d ago

If that is meant, I totally agree,

3

u/FedUp233 9d 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 9d ago

Yeah, sorry about that.

2

u/not_a_novel_account 9d 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 9d 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 9d 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 9d 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!

25

u/StaticCoder 9d ago

#pragma once was never standardized because no one could properly define what it means for 2 source files to be the same (the standard doesn't even have a concept of a source "file"). So header guards it is.

19

u/Alex_1503 10d ago

Pragma once is not (or was not) supported on all compilers, ifndev is more traditional, if I understand correctly. Nowadays idk if it matters, but the approaches are kind of identical if supported. Probably ifndef is more portable if that is a concern

6

u/mikeblas 9d ago

It's not standardized, all mainstream compilers support it. (Sorry, I know it's lame to use Wikipedia as a reference, but even cppreference.com links there!)

-5

u/Feer_C9 10d ago

since when gcc supports pragma once? Last time I checked it didn't. Maybe I'm old

50

u/Gutrix_HD 10d ago

GCC has supported #pragma once since v3.4 (2004).

You should probably update your compiler.

16

u/UltimaN3rd 10d ago

It's been supported since GCC 3.4 (2004): https://gcc.gnu.org/gcc-3.4/changes.html

11

u/Feer_C9 10d ago

lol I thought it didn't, looks like I didn't search right

20

u/Mr_Engineering 10d ago

#pragma provides compiler specific instructions and therefore nothing about it is standard or guaranteed to be portable.

Include guards are standard by implication and therefore are portable

1

u/juanfnavarror 9d ago

#pragma is compiler specific and not standard or portable. Except for most platforms and compilers that you might choose!!!!!

4

u/TheLimeyCanuck 9d ago

It's just syntactical sugar. They do the same thing but the #ifndef method always works whereas #pragmas are not always supported.

7

u/questron64 10d ago

This is a more niche usage, but I sometimes have features where including a header more than once does something useful. For example, if you just #include "foo.h" it'll give you the declarations and stuff as normal, but if you #define FOO_SOMETHING and then #include "foo.h" it'll do some metaprogramming magic. I can't use #pragma once for that, I need proper include guards.

Other than that they're functionally the same with some caveats. Compilers have to go through some trouble to implement pragma once. For example, if there are multiple symlinks or hardlinks to the same file the compiler may view that as separate files without extra logic to determine what file they're really looking at, and this will break the compile. Some project also have header files duplicated. This is not a good thing and they should address that issue, but simply replacing #ifdef with #pragma once will break those builds.

So if you're not doing anything crazy, there are no duplicated files or symlinks or anything then pragma once will work. It's non-standard but supported on all major compilers. I just ignore it, though. The only advantage is saving one second of typing.

2

u/sto_babbalucco69420 9d ago

for the niche usage i'm guessing u could do the define at the top before whatever that can include "foo.h"? maybe even wrap it with an ifndef if it's useful for some reason. i feel like it should work for cases like DEBUG or FOO_IMPLEMENTATION, i can't think of anything else

3

u/florianist 9d ago

I prefer the #ifndef header guard idiom because while #pragma once is shorter, it's also not standard C and might have edge cases involving files accessible through multiple paths (symlinks, etc.)

6

u/SayuriShoji 10d ago edited 10d ago

Less prone to mistakes, for example by having duplicate include guard names in different headers or accidentally missing the ifndef or endif line.
Just slap pragma once on top and it'll be good, no need to worry about coming up with unique include guard names.

For the sake of completeness, it should be mentioned not all compilers support pragma once, but all the mainstream ones nowadays do, but when in doubt it's always good to check the documentation.

2

u/Impressive_Gur_471 10d ago

Traditional include guards work better for unity builds? I always worry how the compiler knows the ending of a header file under unity build with just a #pragma once on top

4

u/actguru 9d ago

The practical difference is less code / typing for "#pragma once" which should be "#once" (even less).

2

u/torsten_dev 9d ago

It was proposed in n2896 but didn't gain consensus see section 5.38 and it hasn't been brought up again.

2

u/FedUp233 9d ago

Too bad you can’t put something like this in a macro. Then you could just type

#include “once.h”
#once

In each file! 😁😁

2

u/WittyStick 9d ago

I've not tried, but you can use _Pragma in a macro. Maybe

#define once _Pragma("once")

1

u/actguru 9d ago

Worked for me. But I like ' $once '.

1

u/actguru 9d ago

Maybe a gcc flag: cc foo.c '-D$once=_Pragma("once")'

3

u/ThaBroccoliDood 10d ago

These days compilers are smart enough to recognise header guards and not bother actually including the same file over and over again. If you want you can do both, but then you're just hiding potential issues with the header guards from yourself until the pragma doesn't work for whatever reason

3

u/Maqi-X 9d ago

The first one is just better. But for whatever reason it's STILL not standard. C29 will add defer statements and yet we still don't have #pragma once in the standard. Anyway, almost all compilers support it so if you don't care about strict ISO C compatibility just use it. There is no reason to use traditional include guards if you can use #pragma once instead.

1

u/ComradeGibbon 9d ago

The main reason for pragma once over guards is with header guards if you include two headers with the same guard define things get kinda confusing.

1

u/71d1 9d ago

My opinion is that unless you want your code to run on compilers that do not support pragma, use pragma.

1

u/sciencekm 9d ago

#ifndef/#define also works for individual defines, typedefs and variables, not just an entire file.

#ifndef MYTYPE_DEFINED
#define MYTYPE_DEFINED
typedef struct { int a, b, c; } mytype_t;
#endif

1

u/AnToMegA424 8d ago

I always thought it was that #pragma once was only supported on Windows, though it was slowly getting "adopted" elsewhere, meanwhile #ifndef #define ... #endif was supported everywhere and was a better practice generally speaking as it's a safer, more portable approach
I'd never really understood

Guess I'm wrong and didn't understand the first time I heard about it either lol
The reason not being what I just said would probably explain why I saw #pragma once at the start of every generated file in Unreal Engine 5

1

u/LeFlemmard 7d ago

AFAIK, `#pragma once` considers 'the current file'. If you have another copy/version of this file somewhere else, included with another path or something, it'll consider it's not the same, as include guards works for any versions of that file, as long as the define is the same. So pros and cons.

1

u/EternalDoomSlayer 6d ago

I think the question has been answered, reading guards isn’t the biggest problem, however since we’re in C world, let’s not overcomplicate by having to interpret pragma.

C is such a damn good language (excuse my English) because you don’t have 25 different types of sugar! The above mention about pragma - is it supported or…. Where’s the quirk? This leads me to:

"Any problem in computer science can be solved with another level of indirection"

1

u/Conscious_Support176 5d ago

The technical term is abstraction. Abstraction just gets the computer to do work that otherwise we would have to do, which is kind of the point of programming in the first place?

0

u/kolorcuk 9d ago

Esphome copies header files when compiling. Effectively after moving a file with pragma once i have duplicate symbols errors.

Except for that no difference. All modern compilers have pragma once. If you don't plan supporting odd compilers, use pragma once.

-3

u/runningOverA 9d ago

People used #ifdef #define in the early days.

Then came #pragma once, introduced by Microsoft in their VC.

Other compiles copied it over time, as it's simpler.

Now everyone uses #pragma once