c++header-files

including a header file twice in c++


What happens if I include iostream or any other header file twice in my file? I know the compiler does not throw error.

Will the code gets added twice or what happens internally?

What actually happens when we include a header file ?


Solution

  • Include guard prevents the content of the file from being actually seen twice by the compiler.

    Include guard is basically a set of preprocessor's conditional directives at the beginning and end of a header file:

    #ifndef SOME_STRING_H
    #define SOME_STRING_H
    
    //...
    
    #endif 
    

    Now if you include the file twice then first time round macro SOME_STRING_H is not defined and hence the contents of the file is processed and seen by the compiler. However, since the first thing after #ifdef is #define, SOME_STRING_H is defined and the next time round the header file's content is not seen by the compiler.

    To avoid collisions the name of the macro used in the include guard is made dependent on the name of the header file.