including a header file twice in c++

前端 未结 5 1758
失恋的感觉
失恋的感觉 2021-01-01 17:03

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

5条回答
  •  南笙
    南笙 (楼主)
    2021-01-01 17:43

    When you include a header file, all its contents get copied to the line where the "#include" directive was placed. This is done by the preprocessor and is a step in the compilation process.

    This process is the same for standard files like iostream or user-made ".h" files stored in local directory. However, the syntax slightly differs.

    We use #include for files like 'iostream' which are stored in the library. Whereas, for header files in the local directory, we use #include "filename.h".

    Now, what if we include header files twice:

    Ideally speaking the content should be copied twice. But...

    1. Many header files use the modern practice of mentioning #pragma once which instructs the pre-processor to copy contents only once, no matter how many times the header file is included.

    2. Some very old codes use a concept called 'include gaurds'. I won't explain it as the other answers do so very well.

    Using pragma once is the easy and the modern approach, however, include guards were used a lot previously and is a relatively complicated fix to this issue.

提交回复
热议问题