4

I see in some header files of the C++ Standard Library (e.g: istream) that both #pragma once and #ifndef/#define include guards. I'm using MS Visual Studio 2010 Express.

For example:

#pragma once
#ifndef _ISTREAM_
#define _ISTREAM_
.
.
.

Why both are used ?

Maged Elghareib
  • 119
  • 2
  • 9
  • 2
    Keep in mind, the standard library is written for a particular compiler. It can do things that are not portable. In fact, one of the reasons for putting things in the standard library is that they can't be implemented portably (for example, `offsetof`). Don't take the standard library as an exemplar of how you should write code. (Another example is that include guard: the name `_ISTREAM_` is reserved for use by the implementation) – Pete Becker Jul 21 '17 at 15:16

2 Answers2

3

if #pragma once is supported, it leads to faster compile times, since the compiler only includes the file once. #ifndef still includes the file again, but all the text in between is stripped out by the preprocessor (since the #define was already evaluated earlier, and thus is defined).

There's a discussion on it here: #pragma once versus #ifndef

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
blakery
  • 71
  • 4
0

This is likely for cross-compatibility. Pragma once is widely supported, but not necessarily part of the standard.

Have a look at: #pragma once vs include guards?

drone6502
  • 433
  • 2
  • 7