Is it good practice to use your choice of either/both include guards and #pragma once
in every header file, or just those with something such as a class declaration?
I am tempted to put it in every header, but I'm afraid it would be unneeded and only add to the compile time. What is good practice or common to do?
Let me clarify: I understand the difference between the two. I am asking whether by experience programmers use it in every file or just those that require it.
Always write internal #include guards. Never write external #include guards.
In the C and C++ programming languages, an #include guard, sometimes called a macro guard, header guard, or file guard, is a particular construct used to avoid the problem of double inclusion when dealing with the include directive.
In the absence of #include guards around #include directives, the use of #pragma once will improve compilation speed for some compilers since it is a higher-level mechanism; the compiler itself can compare filenames or inodes without having to invoke the C preprocessor to scan the header for #ifndef and #endif .
Include guards are used so that the include file can be included multiple times in a single compilation unit without resulting in duplicate declarations. Do not use include guards when the file should be included multiple times in a single compilation unit and this does not result in duplicate declarations.
Summarizing the comment by Galik and what I realized:
Include guards should be put in every header file in the case that something in the future conflicts. Furthermore, the small time it takes the compiler to process the include guards will make the compilation faster since the extra header does not need to be processed.
#pragma once
is compiler specific, while normal include guard definitions, should work with any c++ preprocessor.
Thus for sake of portability, always stick to "ye good old" include guards idiom.
The use of include guards is essential to prevent multiple symbol declaration errors in your code. You shouldn't bother about assumptions, or implications, how this is handled by the c++ preprocessor (modern ones are pretty optimized to do this efficiently).
If you want your code to be portable to all C++ compilers you'll need to use include guards. If you feel the compiler you use is inferior and benefits from the use of #pragma once
you can also add this pragma: compilers not understanding it will just ignore it. Personally, I don't bother with use of #pragma once
. It is a solution to a non-existing problem: compilers can absolutely detect include guards to avoid opening files already included.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With