Does "#pragma once" have the potential to cause errors?
Asked Answered
P

2

5

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.

Pointing answered 28/5, 2012 at 4:13 Comment(3)
I don't really know C/C++, but this MSDN article seems to suggest that unrecognized ones are ignored.Valediction
possible duplicate of Is #pragma once a safe include guard?Sororicide
See also Why isn't C/C++´s #pragma once an ISO standard?Sororicide
G
10

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.

Groscr answered 28/5, 2012 at 4:24 Comment(0)
K
5

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.

Krakow answered 28/5, 2012 at 4:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.