Login    New User    Forgot Password    Help      

Header files


Header files

Code files (with a .cpp extension) are not the only files commonly seen in programs. The other type of file is called a header file, sometimes known as aninclude file. Header files almost always have a .h extension. The purpose of a header file is to hold declarations for other files to use.



library is a package of code that is meant to be reused in many programs. Typically, a library includes a header file that contains declarations for everything the library wishes to expose (make public) to users, and a precompiled object that contains all of the implementation code compiled into machine language. These libraries typically have a .lib or .dll extension on Windows, and a .a or .so extension on Unix. Why are libraries precompiled? First, since libraries rarely change, they do not need to be recompiled often, if ever. It would be a waste of time to compile them every time you wrote a program that used them. Second, because precompiled objects are in machine language, it prevents people from accessing or changing the source code, which is important to businesses or people who don’t want to make their source code available for intellectual property reasons.

Writing your own header files

Now let’s go back to the example we were discussing in the previous lesson. When we left off, we had two files, add.cpp and main.cpp, that looked like this:


int add(int x, int y)
      return x + y;


main.cpp that includes add.h:

#include <iostream>
  #include "add.h" // this brings in the declaration for add()
  int main()
      using namespace std;
      cout << "The sum of 3 and 4 is " << add(3, 4) << endl;
      return 0;

When the compiler compiles the #include "add.h" line, it copies the contents of add.h into the current file. Because our add.h contains a function prototype for add(), this prototype is now being used as a forward declaration of add()!

Consequently, our program will compile and link correctly.


Angled brackets are used to tell the compiler that we are including a header file that was included with the compiler. The double-quotes tell the compiler that this is a header file we are supplying, which causes it to look for that header file in the current directory containing our source code first.