Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#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?

like image 559
Shan Avatar asked Apr 14 '13 01:04

Shan


2 Answers

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.
like image 133
lvella Avatar answered Nov 15 '22 18:11

lvella


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).

like image 34
clark Avatar answered Nov 15 '22 18:11

clark