我是否应该仍然使用#include警卫和#pragma一次? [英] Should I still use #include guards AND #pragma once?
问题描述
http://en.wikipedia.org/wiki/Pragma_once
当所有这些编译器均支持#pragma once
时,我仍应使用include防护吗?
关于堆栈溢出的许多响应都说要同时使用这两种兼容性,但是我不确定这是否仍然正确.
当今哪些编译器不支持#pragma once
?
http://en.wikipedia.org/wiki/Pragma_once
Should I still use include guards when all of these compilers support #pragma once
?
A lot of responses on stack overflow say to use both for compatibility, but I'm not sure if that still rings true.
What compilers today don't support #pragma once
?
我不确定同时使用这两种方法是否只是推荐,否则是否仍然有很好的理由使用这两种方法.
仅在使用#pragma once
时会引起问题的任何示例吗?
I am not sure if using both was just a recommendation before it became widley adopted, or if there are still very good reasons to use both methods.
Any examples of when only using #pragma once
will cause problems?
推荐答案
这取决于程序的可移植性.
It depends on how much portable your program is expected to be.
只要编写的程序可以与肯定支持#prama once
的编译器一起使用,只需使用#pragma once
就足够了.但是这样做会限制您的程序使用支持实现定义功能的编译器集.
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.
如果您需要程序在所有编译器上运行,则应使用#pragma once
并同时包含防护.
If you need your program to work on all compilers then you should use #pragma once
and include guards both.
如果编译器不支持#pragma once
,它将简单地忽略它 [Ref#1] ,在这种情况下,标题保护将达到您的目的,因此使用它们没有错当您不了解目标编译器支持的功能时,都可以使用.
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.
因此,如果您希望程序在不同的编译器上具有100%的可移植性,那么理想的方法仍然是仅使用包含保护.正如@CharlesBailey正确指出的那样,由于#pragma once
的行为是由实现定义的,因此未知编译器上的行为可能会对您的程序产生不利影响.
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]
标准C ++ 03:16.6 Pragma指令
形式的预处理指令
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.
这篇关于我是否应该仍然使用#include警卫和#pragma一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!