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

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

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

#pragma once
#ifndef HEADER_H
#define HEADER_H

...

#endif // HEADER_H

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


当前回答

性能的好处在于,一旦读取了#pragma,就不必重新打开文件。使用保护,编译器必须打开文件(这可能会浪费时间)来获得它不应该包含它的内容的信息。

这只是理论上的,因为对于每个编译单元,一些编译器将自动不打开没有任何读取代码的文件。

无论如何,并不是所有编译器都是这样,所以理想情况下,#pragma一旦出现就必须避免,因为跨平台代码根本就不是标准的/没有标准化的定义和效果。然而,实际上,它确实比守卫要好。

最后,在不检查每个编译器的行为的情况下,确保编译器具有最佳速度的更好建议是一次性使用pragma和守卫。

#ifndef NR_TEST_H
#define NR_TEST_H
#pragma once

#include "Thing.h"

namespace MyApp
{
 // ...
}

#endif

这样你就可以获得两者的优势(跨平台和帮助编译速度)。

由于打字时间较长,我个人使用一种工具来帮助生成所有这些信息(Visual Assist X)。

其他回答

我使用它,我很高兴,因为我必须键入更少,使一个新的标题。它在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.

不总是正确的。

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=52566有一个很好的例子,其中包括两个文件,但由于时间戳和内容相同(不相同的文件名),误以为它们是相同的。

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.

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

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