Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 621
Trevor Hickey Avatar asked May 28 '12 04:05

Trevor Hickey


People also ask

What you mean by does?

present tense third-person singular of do.

Does meaning and examples?

“Does” is used for singular subjects like “he,” “she,” “it,” “this,” “that,” or “John.” “Do” is used to form imperative sentences, or commands. Example: Do your homework. “Does” is never used to form imperative sentences.

What type of word is do?

Do is an irregular verb. Its three forms are do, did, done. The present simple third person singular is does: Will you do a job for me?

What's the full meaning of DOS?

A DOS, or disk operating system, is an operating system that runs from a disk drive. The term can also refer to a particular family of disk operating systems, most commonly MS-DOS, an acronym for Microsoft DOS.


2 Answers

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.

like image 102
Alok Save Avatar answered Oct 08 '22 23:10

Alok Save


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.

like image 30
Karolis Juodelė Avatar answered Oct 08 '22 21:10

Karolis Juodelė