Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
741 views
in Technique[技术] by (71.8m points)

c++ - Include guard and #pragma once in the same header file

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...