Does “#pragma once” have the potential to cause errors?

时光怂恿深爱的人放手 提交于 2019-12-23 09:49:15

问题


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 */

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 */

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


回答1:


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.

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]
Standard C++03: 16.6 Pragma directive

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.




回答2:


The standard says "Any pragma that is not recognized by the implementation is ignored.", so you're probably fine, even if a compiler doesn't know #pragma once.



来源:https://stackoverflow.com/questions/10779262/does-pragma-once-have-the-potential-to-cause-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!