Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why using both #pragma once and include guard? [duplicate]

I am studying boost libraries, and something strange to me is many libraries use this kind of code:

#ifndef BOOST_SERIALIZATION_ACCESS_HPP
#define BOOST_SERIALIZATION_ACCESS_HPP

// MS compatible compilers support #pragma once
#if defined(_MSC_VER)
# pragma once
#endif

MSDN explicitly states that:

There is no advantage to use of both the #include guard idiom and #pragma once in the same file

I can't understand what might the reason be. include guard does the job anyway so why we bother to write pragma once too?

like image 657
shayan Avatar asked Aug 31 '25 02:08

shayan


1 Answers

Actually there might be a small difference inside the compiler. When compiler encounters #pragma once then it can internally mark that this file is included. When it encounters #include for this file for the second time it won't bother even to open it, it will just ignore the #include statement.

With only include guard the preprocessor has to parse the whole file every time it's included to find a matching #endif. Theoretically, if really complicated and large include files are included multiple times this can affect compilation time.

Other than that, include guard and #pragma once behave the same way. Both of them are usually used because #pragma once is not guaranteed to be supported on all compilers.

Edit:

Compiler might have the ability to detect that include guard's statements are surrounding the whole file's code and deduce that it's an include guard, producing exactly the same behavior as with #pragma once. If that's the case then MSDN's claim is correct.

like image 78
BJovke Avatar answered Sep 02 '25 17:09

BJovke