我读到过,使用#pragma一次可以优化编译器,从而加快编译速度。我知道这是不标准的,因此可能会带来跨平台兼容性问题。

非windows平台(gcc)上的大多数现代编译器都支持这一点吗?

我希望避免平台编译问题,但也希望避免备用保护的额外工作:

#pragma once
#ifndef HEADER_H
#define HEADER_H

...

#endif // HEADER_H

我应该担心吗?我还需要在这上面花费更多的精力吗?


当前回答

如果我们使用msvc或Qt(到Qt 4.5),因为GCC(到3.4),msvc都支持#pragma一次,我可以看到没有理由不使用#pragma一次。

源文件名通常与类名相同,我们知道,有时我们需要重构,重命名类名,那么我们也必须改变#include XXXX,所以我认为手动维护#include xxxxx不是一个聪明的工作。即使使用Visual Assist X扩展,维护“xxxx”也不是一项必要的工作。

其他回答

Additional note to the people thinking that an automatic one-time-only inclusion of header files is always desired: I build code generators using double or multiple inclusion of header files since decades. Especially for generation of protocol library stubs I find it very comfortable to have a extremely portable and powerful code generator with no additional tools and languages. I'm not the only developer using this scheme as this blogs X-Macros show. This wouldn't be possible to do without the missing automatic guarding.

我使用它,我很高兴,因为我必须键入更少,使一个新的标题。它在Windows、Mac和Linux三个平台上都运行得很好。

我没有任何性能信息,但我相信,与解析c++语法的缓慢相比,#pragma和include守卫之间的差异将是微不足道的。这才是真正的问题。例如,尝试用c#编译器编译相同数量的文件和行,看看有什么不同。

最后,使用guard或pragma根本不重要。

Using '#pragma once' might not have any effect (it is not supported everywhere - though it is increasingly widely supported), so you need to use the conditional compilation code anyway, in which case, why bother with '#pragma once'? The compiler probably optimizes it anyway. It does depend on your target platforms, though. If all your targets support it, then go ahead and use it - but it should be a conscious decision because all hell will break loose if you only use the pragma and then port to a compiler that does not support it.

#pragma once确实有一个缺点(除了不是标准的),那就是如果你在不同的位置有相同的文件(我们有这样的情况是因为我们的构建系统会四处复制文件),那么编译器会认为这些是不同的文件。

使用#pragma一次应该适用于任何现代编译器,但我不认为有任何理由不使用标准的#ifndef include guard。它工作得很好。需要注意的是,GCC在3.4版之前一次都不支持#pragma。

我还发现,至少在GCC上,它可以识别标准的#ifndef include guard并对其进行优化,因此它应该不会比#pragma慢很多。