Header Files

  • Contain declarations to be used in .cpp source code files
  • end with a .h extension
  • aka include file
  • Consist of:
    • Include (/ Header) Guard, which consists of conditional compilation directives:
      • #ifndef header_name
      • #define header_name
      • ... code definitions ...
      • #endif
  • Code Body


Example header file:

#ifndef MULTIPLY
#define MULTIPLY
int multiply(int, int);  //forward declaration


To use a header file, it has to be included by the preprocessor keyword #include followed by the name of the required header file:

#include <iostream>

#include "myHeader.h"


Angle brackets indicate files that come with the compiler/OS, whereas self created header files are included by stating their file name within double quotes.


Best practice

  • Use UPPERCASE for the header identifier
  • Always use include guards, to ensure the compiler doesn't try to duplicate a header file that has already been included in another file
  • Generally should only be used for declarations. Leave the implementations in .cpp files
  • Make them as specific as possible, just concentrating on one aspect


Compilation process:

  1. The preprocessor strips out all comments and replaces all code specified by the #include with copies of the actual code within those files
    1. The output is in the form of preprocessed source code, which is sent to the standard output
    2. The following command stops after the preprocessing stage and does not run the compiler proper:
      1. g++ -E main.cpp
  2. The compiler converts the source code to assembler code
    1. The following command stops after the compilation stage:
      1. g++ -S main.cpp
      2. creates a file with a .s extension containing assembly code
  3. The assembler converts the assembly code into object code
    1. The following command stops after the assembler stage:
      1. g++ -c main.cpp
      2. creates a file with a .o extension containing object code
  4. The linker converts all object and required linked files to produce an executable / binary file


The following command takes two .cpp files, and an included header file (specified via its #include statement):

g++ main.cpp multiply.cpp -o multiply




Leave a Reply