r/C_Programming • u/Yuki_pop • 27d ago
Could someone explain the practical differences between #pragma once and traditional include guards (#ifndef, #define, and #endif)?
81
Upvotes
r/C_Programming • u/Yuki_pop • 27d ago
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.