是否执行一次"#pragma"有可能导致错误? [英] Does "#pragma once" have the potential to cause errors?

查看:138
本文介绍了是否执行一次"#pragma"有可能导致错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所有的头文件都使用 include防护以及一次 pragma :

All of my header files use include guards as well as pragma once:

#pragma once
#ifndef FILE_NAME_H
#define FILE_NAME_H

class foo
{
    //foo interface..
};

#endif /* FILE_NAME_H */

我了解 pragma一次不是标准的,并且在各个编译器中可能都不相同,但是是否有可能引起和出错? 以某种方式测试它是否首先可用会更好吗?

I understand that pragma once is not standard and may not be the same across compilers, but is there any chance it will cause and error? Would it be better to somehow test if it's available first?

#ifdef THIS_COMPILER_SUPPORTS_PRAGMA_ONCE
    #pragma once
#endif

#ifndef FILE_NAME_H
#define FILE_NAME_H

class foo
{
    //foo interface..
};

#endif /* FILE_NAME_H */

我想提供一次 pragma 作为可能加快编译速度并避免名称冲突的选项,同时仍然提供跨编译器的兼容性.

I want to provide pragma once as an option to possibly speed-up compilation and avoid name-clashing, while still providing compatibility across compilers.

推荐答案

如果不支持#pragma once,它将被忽略 [Ref#1] ,标题卫士将为您服务,因此,同时使用它们并没有错,您真的不需要检查#pragma once的支持.

If #pragma once is not supported it will simply be ignored[Ref#1] and header guards will serve you the purpose, so nothing wrong in using them both, you don't really need any check for the support of #pragma once.

所以理想的方法是同时使用#pragma once和包含防护,并且您拥有可移植的代码,这些代码也可以利用编译器可能支持的#pragma once优化.

So the ideal way is to use both #pragma once and include guards and you have a portable code that can also take advantage of #pragma once optimization's the compiler may support.

[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.

这篇关于是否执行一次"#pragma"有可能导致错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆