dubnde
dubnde

Reputation: 4441

What is the reason for #pragma once inside header guards?

Just seen this inside <boost/asio.hpp>

#ifndef BOOST_ASIO_HPP
#define BOOST_ASIO_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

/// ....

#endif // BOOST_ASIO_HPP

Disregarding the _MSC_VER preprocessor checks, what is the benefit of having the #pragma once in this case? Doesn't the preprocessor header guard ensure in all cases and on all platforms, the header contents are only ever included once?

Upvotes: 18

Views: 7737

Answers (5)

Skizz
Skizz

Reputation: 71070

You can reproduce the effect of the #pragma once in a standard way using the following:

#if !defined GUARD_SYMBOL
#include "GUARDED_FILE"
#endif

although it is much more verbose. As others have said, it helps with compilation times since the file is not searched for / opened instead of opening the file and ignoring everything inside it - the file still has to be parsed by the preprocessor.

Upvotes: 0

peterchen
peterchen

Reputation: 41096

#pragma once has the same purpose, but include guards are intended to require a deeper analysis to ensure a file is included exactly once - e.g.

// somerandomfileinmyproject.cpp
#undef BOOST_ASIO_HPP 
#include <bost/asio.cpp>

Unless the compiler does handle such cases correctly, it still needs to open the file and pass it through the preprocessor even though it has been included before.

Upvotes: 0

Aoi Karasu
Aoi Karasu

Reputation: 3825

#pragma once specifies that the file will be included (opened) only once by the compiler when compiling a source code file. This can reduce build times as the compiler will not open and read the file after the first #include of the module.

If you don't #pragma once, the file will be opened each time it is needed and compiler will stop parsing it on #ifndef BOOST_ASIO_HPP, if it has been defined.

Upvotes: 21

ckv
ckv

Reputation: 10830

Yes header guards ensures that the header contents are included only once. but here you are using #pragma for checking another definition and not include file.

The below link is existing question on header guards in SO.

Purpose of Header guards

Upvotes: 0

Related Questions