Should I still use #include guards AND #pragma once?

ぐ巨炮叔叔 提交于 2019-12-03 23:27:30

It depends on how much portable your program is expected to be.

As long as you are writing a program which is supposed to work with compilers which you know definitely support #prama once, just using #pragma once should suffice. But doing so you restrict your program to set of compilers which support the implementation defined feature.

If you need your program to work on all compilers then you should use #pragma once and include guards both.

In case a compiler does not support #pragma once it will simply ignore it[Ref#1], in such a case the header guards will serve you the purpose, so nothing wrong in using them both when you are not aware of features supported by your target compilers.

So if you want your program to be 100% portable on different compilers the ideal way is still to use only the include guards. As @CharlesBailey rightly points out since the behavior for #pragma once is implementation defined, the behavior on an unknown compiler might have a detrimental effect on your program.


[Ref#1]
Standard C++03: 16.6 Pragma directive

A preprocessing directive of the form

# pragma pp-tokensopt new-line

causes the implementation to behave in an implementation-defined manner. Any pragma that is not recognized by the implementation is ignored.

It's non-standard so if you want to be safe use the include guards

As your table shows it is very rare now to encounter a compiler in mainstream use that does not support #pragma once. To keep a code base clean and cheap to maintain requires a constant effort of refactoring. Having to update include guards each time you rename a class or move some code around adds a significant burden to this effort.

So I would say apart from some niche corner cases or for broken build systems #pragma once is in practice safe to rely on. If you care about productivity and code quality using only #pragma once seems the obvious choice.

The exceptions being if you're writing a library that needs to support every compiler under the sun or are unfortunate enough to have to work with one of these rare compilers that does not have this feature.

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