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

7

u/questron64 27d 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 27d 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