Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include guard and #pragma once in the same header file

Tags:

c++

boost

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?

like image 792
Tryer Avatar asked Oct 19 '25 22:10

Tryer


1 Answers

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.

like image 170
Cory Kramer Avatar answered Oct 22 '25 12:10

Cory Kramer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!