4

Quoting from Microsoft documentation, There is no advantage to use of both the #include guard idiom and #pragma once in the same file.

Answers to previous related questions on stackoverflow also confirm that it is pointless to have both. See below, for instance:

Header guards and pragma once

The boost library's vector.hpp file, however, starts thus:

#ifndef BOOST_ASSIGN_STD_VECTOR_HPP
#define BOOST_ASSIGN_STD_VECTOR_HPP

#if defined(_MSC_VER)
# pragma once
#endif
...
#endif

That is, it includes both the guard idiom as well as the pragma once. Is there any reason why boost header files have both?

Tryer
  • 3,580
  • 1
  • 26
  • 49
  • 3
    It is an optimization, #pragma once is much faster since the preprocessor can simply skip the entire file. An include guard requires it to keep parsing to find the #endif. So it is still sensible, albeit that the amount of time saved isn't going to be enormous. – Hans Passant Oct 23 '17 at 14:33
  • @HansPassant since in the above vector.hpp file, pragma once is encountered within the include guard, will not the parsing have to happen until the endif is encountered anyway? That is, should not pragma once come before and ahead of include guard? – Tryer Oct 23 '17 at 14:39
  • 1
    @Tryer it probably doesn't matter, because as soon as `#pragma once` is seen by the MS compiler, the whole wile will be skipped anyway. – Jabberwocky Oct 23 '17 at 14:42

1 Answers1

3

Technically #pragma once is not standard C++, whereas header guards are. They will not conflict with each other if you have both.

The reason boost likely has both, as alluded to by the #if defined(_MSC_VER) is that if you're not using MSVC then you need something to act as your header guard, so they fall back to the other method.

Since boost strives to be cross-platform they are trying to ensure their code works on compilers that don't support #pragma once, though all of the big modern compilers I can think of do support it, as enumerated on wikipedia.

sehe
  • 374,641
  • 47
  • 450
  • 633
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Since include header guard is more general, and it is placed first, it is unclear to me why something more specific (pragma once) should follow it. – Tryer Oct 23 '17 at 14:35
  • 2
    @Tryer - Who says that there **is** an advantage? The Boost vector.hpp has a copyright starting in 2005 and by then would probably support compilers from the late 1900's. **Now** Microsoft says that there is no advantage, but there might have been earlier and it doesn't do much damage to keep it in. – Bo Persson Oct 23 '17 at 15:24