Does “#pragma once” have the potential to cause er

2019-06-22 12:18发布

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.

2条回答
Bombasti
2楼-- · 2019-06-22 12:45

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.

查看更多
迷人小祖宗
3楼-- · 2019-06-22 12:45

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.

查看更多
登录 后发表回答