Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

same header file in multiple source files in a c++ program

Tags:

c++

header

g++

If the same header file is included in multiple source files in a c++ program , then how does it effect the compilation ( Especially g++ ) ?

Will the compiler load the header file only once and compile it for every source file that includes the header or the header file will be loaded separately for every source file that includes it .

like image 472
Biraj Bora Avatar asked May 31 '13 06:05

Biraj Bora


1 Answers

Most header files have special protection against multiple includes like

#ifndef MY_HEADER_H
#define MY_HEADER_H

// header body...

#endif MY_HEADER_H

Without this protection, header may be included more than once and this may cause compilation or linking errors.

Compiler may be smart enough to avoid reading file more than once. But, even if it did not, operating systems are very good at caching files which were recently read, and this will load very, very quickly - almost at no cost.

like image 113
mvp Avatar answered Sep 29 '22 07:09

mvp