Shan
Shan

Reputation: 3067

#include <iostream> in multiple files

I hope this hasn't been asked before on this site. I wasn't able to find a solid answer from google.

What happens when you #include iostream in multiple files of a project? I always use #ifndef and #define in my header files. Does that prevent iostream from being included more than once?

Upvotes: 6

Views: 7232

Answers (4)

Vivraan
Vivraan

Reputation: 163

#ifndef __IOSTREAM_H
#include <iostream>
#endif

...

Seems that most standard headers have a sort of include guard as above.

Alternately you could make your own include guard by defining the required macro.

Upvotes: 0

lvella
lvella

Reputation: 13481

I had two interpretations of this question:

  1. Can you include iostream multiple times in the same compilation unit?
    • Yes, safely. All standard headers have include guards so to allow this usage safely.
  2. Will using include guards yourself in your code prevent iostream from be included multiple times?
    • Surely, as well it would prevent everything in between #ifndef and #endif (or in a header marked with #pragma once, in compilers that support it) from being seen by the compiler more than once... it is just what include guards does, right? But that is not really needed for #include <iostream>, because it is already guarded from multiple inclusions.

Upvotes: 6

clark
clark

Reputation: 395

Like chris and Haroogan said, yes they will prevent that. What the #ifndef and #define are are pre-processor instructions, and are translated in english to

#ifndef (if undefined)

#define (define)

So if you make a header, and #include "myheader.h" twice, then the file will not be included again because you encompassed it in an if statement, which will cause the file to only be included(and defined) when it has not yet been included(defined).

Upvotes: 3

Zanven
Zanven

Reputation: 154

regardless. you still attempt to include it multiple times even thow you use ifndef. because the multiple files will be included once. and all attempt to include <iostream> but if you open <iostream> it has

#pragma once

which basically means it will only ever be included once. it is not the advised way to avoid multiple includes i find in the industry. because its harder to know that it wont be included again. compared to seeing ifndef's on the top and bottom.

Upvotes: 0

Related Questions