Search code examples
c++cheader-files

Do compilers compile all included header files along with the main program every time we compile that program?


According to Wikipedia this is what the C preprocessor does:

"The preprocessor replaces the line #include <stdio.h> with the text of the file 'stdio.h', which declares the printf() function among other things."

So if this is true, a program which includes more header files would take more time to compile?


Solution

  • So if this is true, a program which includes more header files would take more time to compile?

    Of course. Strictly speaking, the more code the compiler needs to look at, the more time it needs to process it. For some really big projects, the amount of time needed to look at all the files easily becomes a concern. This is especially true for extraordinarily large and/or complex template code, which for practical reasons must reside in header files. The organization of the header files themselves also have an impact on compilation time.

    However, it's not as simple as you think it is. It is highly dependent on the quality of implementation (QOI) of the compiler, and modern compilers nowadays are actually quite good at handling header files in most cases.

    For example, GCC specifically recognizes include guards to reduce processing time. And compilers nowadays are getting much better at handling complex template code e.g. most of the standard library. On VC++ compilers, including windows.h (which has function prototypes for almost the entire Windows API) does not appreciably increase compile times in my experience. And if all else fails, many if not all compilers have a "precompiled headers" feature you can use.

    Basically, don't worry about it until it becomes a problem. If having more header files helps to better organize your code, then by all means don't hesitate to use them.