Skip to main content
Engineering LibreTexts

1.3: Header Files

  • Page ID
    29007
  • 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.