#pragma once or #ifndef?

10

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

E

#pragma once

class Foo
{  
   // código
};

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

    
asked by anonymous 17.03.2014 / 20:22

2 answers

9

The big difference is that the header guards ( #ifndef ) use a feature of the standard and are supported by any compiler compiler. Already #pragma has behavior dependent on each compiler. It is the standard way of doing something non-standard. But currently everyone supports #pragma once and you do not really have to worry about finding one that does not have that support.

On what to use, the interesting thing is that #pragma once is more efficient . Compilers usually check the first line of the file first and check that it is a #pragma once and that file has already been loaded. This means that you do not need to do a full parse as you would with #ifndef .

As a negative, #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 both, #pragma once will fail to protect you. But really ... if you have two equal files in your project, something is wrong.

Note: Some compilers also find ways to optimize #ifndef , so performance gains can be negligible.

    
18.03.2014 / 12:25
5

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 .

    
17.03.2014 / 20:27