When to use include guards or #pragma once C++ [closed]

删除回忆录丶 提交于 2019-12-22 05:09:18

问题


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.


回答1:


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.




回答2:


#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).




回答3:


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.



来源:https://stackoverflow.com/questions/27649946/when-to-use-include-guards-or-pragma-once-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!