Skip to main content
Engineering LibreTexts

1.3: Header Files

  • Page ID
    29007
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)

    A Bit More About Header Files

    Just wanted to provide a bit more clarification about header files - to show what actually happens with the preprocessor.

    Let's say we have some code for our big project, and we have some customized functions that we declare in the file foo-1.h. In the code example below we call the function testFoo(), which is is defined in the file foo-1.

    // file: main.cpp 
    #include <iostream> 
    #include "foo-1"
    int main() { 
      int myFoo;
      
      myFoo = testFoo();
      cout << "Returned from testFoo: " << myFoo << endl;
    }

    So, the foo-1 file looks like and simply returns the value defined by our macro which is 99. 

    #define FOOVAL 99
    
    int testFoo() { 
      return FOOVAL;
    }

    The main.cpp outputs:

    Returned from testFoo: 99

    The preprocessor then actually passes the following code to the compiler to convert into an executable program.

    // file: main.cpp 
    // The iostream file code has been ommitted in this example but it would be here.
    
    #define FOOVAL 99
    
    int testFoo() {
      return FOOVAL;
    }
    
    
    int main() { 
      int myFoo;
      
      myFoo = testFoo();
      cout << "Returned from testFoo: " << myFoo << endl;
    }

    This is a simple example and there is a bit more detail that is left out of this example, but hopefully this calrifies what the preprocessor actually does with header files.


    1.3: Header Files is shared under a CC BY-SA license and was authored, remixed, and/or curated by Patrick McClanahan.