r/C_Programming • • 23d 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

Show parent comment

8

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