我读到过,使用#pragma一次可以优化编译器,从而加快编译速度。我知道这是不标准的,因此可能会带来跨平台兼容性问题。
非windows平台(gcc)上的大多数现代编译器都支持这一点吗?
我希望避免平台编译问题,但也希望避免备用保护的额外工作:
#pragma once
#ifndef HEADER_H
#define HEADER_H
...
#endif // HEADER_H
我应该担心吗?我还需要在这上面花费更多的精力吗?
我读到过,使用#pragma一次可以优化编译器,从而加快编译速度。我知道这是不标准的,因此可能会带来跨平台兼容性问题。
非windows平台(gcc)上的大多数现代编译器都支持这一点吗?
我希望避免平台编译问题,但也希望避免备用保护的额外工作:
#pragma once
#ifndef HEADER_H
#define HEADER_H
...
#endif // HEADER_H
我应该担心吗?我还需要在这上面花费更多的精力吗?
当前回答
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.
其他回答
如今,老式的include守卫就像#pragma一样快。即使编译器没有特别对待它们,当它看到#ifndef WHATEVER和WHATEVER被定义时,它仍然会停止。现在打开一个文件非常便宜。即使有改进,也只是毫秒级的改进。
我只是不使用#pragma一次,因为它没有任何好处。为了避免与其他include守卫发生冲突,我使用了如下代码:CI_APP_MODULE_FILE_H——> CI =公司首字母;APP =应用程序名称;其余部分不言自明。
我使用#ifndef/#define include守卫使用包含UUID的符号,如下所示:
#ifndef ARRAY__H_81945CB3_AEBB_471F_AC97_AB6C8B220314
#define ARRAY__H_81945CB3_AEBB_471F_AC97_AB6C8B220314 /* include guard */
#endif
我一直使用能够自动生成uuid的编辑器。 这可以防止与其他库中具有相同基本名称的文件发生名称冲突,并检测文件系统中的多个位置是否放置了完全相同的文件。
缺点是增加了表的大小,因为符号要大得多,但我还没有看到它的问题。
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.
使用#pragma一次应该适用于任何现代编译器,但我不认为有任何理由不使用标准的#ifndef include guard。它工作得很好。需要注意的是,GCC在3.4版之前一次都不支持#pragma。
我还发现,至少在GCC上,它可以识别标准的#ifndef include guard并对其进行优化,因此它应该不会比#pragma慢很多。
GCC从3.4开始支持#pragma一次,参见http://en.wikipedia.org/wiki/Pragma_once获得进一步的编译器支持。
我认为使用#pragma一次而不是包含守卫的最大好处是可以避免复制/粘贴错误。
让我们面对这个问题:我们大多数人很少从头开始一个新的头文件,而只是复制一个现有的头文件并根据我们的需要进行修改。使用#pragma创建一个工作模板比使用守卫要容易得多。对模板的修改越少,遇到错误的可能性就越小。在不同的文件中使用相同的include守卫会导致奇怪的编译器错误,并且需要一些时间来找出哪里出了问题。
#pragma once更容易使用。