Header files contain a bunch of forward declarations that can be used in multiple c++ source code. It removes the duplication of adding same declarations at different places.

We include header files using #include directive. As shown below.

#include <iostream>
int main()
{
  std::cout << "Hello world" << std::endl;
 
  return 0;
}

It copies the content of iostream header file to this file itself. It comes with all the forward declarations of identifiers such as std::cout.

A header file consists of two parts:

  1. header guards
  2. actual content of file, declarations of identifiers.

Header files usually have .h extension and have same base name as source file.

Example

We have three files, main.cpp, add.cpp and add.h.

main.cpp

#include "add.h"
#include <iostream>
 
int main(int argc, char const *argv[])
{
    std::cout << add(1, 2);
    return 0;
}

#include "add.h" should copy the forward declaration for add from add.h header file.

add.h

int add(int, int);

add.cpp

#include "add.h"
int add(int a, int b)
{
    return a + b;
}

It is to be noted that we have included header file in add.cpp also as it makes sure that the definition matches with declaration and give compilation error if does not match. So, it is recommended to include header file in source.

Compiling the program using command,

clang++ -ggdb -std=c++20 main.cpp add.cpp -o add

It is to be noted that we need to provide add.cpp file so that linker can link the definition.

Important

Header files should not have definitions as they can violate ODR.

Angular brackets vs Double quotes

Angular brackets include directives #include <iostream> are used to preprocessor know that the header file should be searched in compiler directories or third party libraries defined using include directories.

Double quotes #include "add.h" tells preprocessor that the header files should be searched in the project directory. If it could not find in the project directory, it will look into include directories.

References

  1. https://www.learncpp.com/cpp-tutorial/header-files/