#pragma Once or #ifndef?

Asked

Viewed 2,414 times

13

I know there are two ways to prevent a header file from being duplicated in C C++:

#ifndef FOO_H_INCLUDED
#define FOO_H_INCLUDED

class Foo
{  
   // código
};

#endif

And

#pragma once

class Foo
{  
   // código
};

Being that the first I see in almost 100% of libraries open source thereabout. So my question is: if the second form is simpler and supported by the major compilers (gcc, msvc, intel, Clang), what’s wrong with using #pragma once? And what a difference these approaches make to the compiler?

2 answers

14


The big difference is that the Guards header (#ifndef) use a standard feature and are supported by any and all conforming compiler. Already a #pragma behavior dependent on each compiler. It is the standard way to do something non-standard. But currently all support the #pragma once and you don’t really have to worry about finding one that doesn’t have that support.

About which to use, the interesting thing is that the #pragma once is more efficient. Compilers usually check the first line of the file first and check if it is a #pragma once and if that file has already been uploaded. This means that it is not necessary to do a full parse as would occur with the #ifndef.

As a negative point, the #pragma once will compare by the absolute path of the file. That is, if you have two exact copies of the same file and include the two, the #pragma once will fail to protect you. But really... if you have two identical files in your project, something is wrong.

Note: Some compilers also find ways to optimize #ifndef, then the performance gain may be negligible.

6

Because #pragma once is not part of the C/C++ standard and is only adopted by some compilers, such as Microsoft Visual Studio. To universalize your code to multiple compilers, the best approach is to use the classic method with #ifndef.

  • 2

    But, if the target compilers support, what difference does it make? It’s unsafe?

  • 3

    @Ianmedeiros, according to wikipedia GCC supports pragma once since version 3.4: http://en.wikipedia.org/wiki/Pragma_once

Browser other questions tagged

You are not signed in. Login or sign up in order to post.