What does the compiler do with multiple #include of same header

What does the compiler do? I mean if you include iostream it includes other #include. What if you included a header file already included in one of you earlier #include? The compiler replaces them right, but does the compiler detect and if so, avoid replacing repeating #includes?
The preprocessor doesn't care if you already included a header and it just replaces #include as usual.
When writing a header is good practice putting header guards:
1
2
3
4
5
//MyHeader.h
#ifndef MY_HEADER
#define MY_HEADER
    // Code here
#endif 
This prevents the code to be replaced multiple times

http://www.cplusplus.com/forum/articles/10627/
Hi Bazzy,

Thanks, so that's what #ifndef is for... thanks again!
Really? Visual Studio throws an error in this situation:

1
2
3
4
5
6
7
8
9
//headerfile1.h
   #include "headerfile2.h"

//headerfile2.h
   #include "headerfile1.h"

//main.cpp
   #include "headerfile1.h"
   #include "headerfile2.h" 

fatal error C1014: too many include files : depth = 1024
Those headers aren't guarded and there's an infinitely recursive inclusion error. The preprocessor is not smart enough to realize when a header is being included more than once in the same recursion branch.
Last edited on
Um sorry 'bout this but i've tried it and it appears im not doing it right? How would I do this:

1
2
3
4
5
 
// Wrong
#ifndef <climits>
#include <climits>
#endif 


Any help?
In Bazzy's example, MY_HEADER is not a placeholder for an actual header. It's a macro the preprocessor defines and it's meant to be used in your headers. The language headers are already guarded, so including them twice does nothing.

For example,
header.h:
1
2
3
4
#ifndef __HEADER_H__
#define __HEADER_H__
//...
#endif 
Last edited on
closed account (z05DSL3A)
climits, will be guarded, so just include it. It is the headers that you write that should be guarded by you.

1
2
3
4
5
6
#ifndef _HEADERFILE1_
#define _HEADERFILE1_

#include"headerfile2.h"

#endif 
headerfile1.h

1
2
3
4
5
6
#ifndef _HEADERFILE2_
#define _HEADERFILE2_

#include"headerfile1.h"

#endif 
headerfile2.h

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <iostream> // is guarded,will have no ill effect

#include "headerfile1.h"
#include "headerfile2.h"

int main()
{

return 0;
}
Ok, it's still not too clear to me but im just beginning and I was just forward-skimming the book im reading. I'll probably understand more after I read about it. thanks Bazzy and helios! And Grey Wolf!
Last edited on
Topic archived. No new replies allowed.