Search code examples
linkercompiler-constructionexecutionpreprocessor

Do Header files execute everytime when we compile the program?


When we add the header files to our program, the main intent is that we have to use their functions and, to use any function it is compiler's job to clarify that it does not have any error. So when we compile our program, does compiler executes all the functions that are written in the included header files?


Solution

  • When we add the header files to our program, the main intent is that we have to use their functions and, to use any function it is compiler's job to clarify that it does not have any error.

    When we #include a header in our source file, the main intent is that the contents of the header be treated as if they appeared, at that point, directly in the source file. The compiler has the same responsibilities toward the resulting aggregate translation unit as it has toward a translation unit that does not #include anything, including identifying and diagnosing violations of language constraints.

    The conventional use of header files in C is to provide declarations of functions and variables defined elsewhere, and to provide definitions of types and macros that may be useful. C header files typically do not include function or variable definitions (as opposed to declarations), as that is troublesome.

    C++ header files serve a similar purpose to C header files, but they often also include inline function definitions, especially of class constructors, destructors, and member functions.

    Again, however, all but the first paragraph of that is conventional use, not language rule. It turns out to be very useful to have headers containing reusable declarations (and inline function definitions) so that we don't have to know or type all of the required declarations of all of the functions and external objects we want to use, but we could, in principle, write the needed declarations by hand into every source file without changing the meaning of the overall code.

    So when we compile our program, does compiler executes all the functions that are written in the included header files?

    No, why would it? The compiler compiles source code, which includes headers, to executable programs and libraries. That does not involve executing anything defined in the program being compiled, regardless of whether it is defined in a header. Functions are executed when one of the resulting programs is run.