Skip to content
Theory · Building and the Preprocessor · lesson 1 of 7

Headers and translation units

The function triple is defined in triple.cpp and called from main.cpp, report.cpp and other files of the program. The compiler accepts each call only if the declaration int triple(int x); comes before it. Copying that declaration into every file by hand is unreliable. If the parameter type changes in one copy and the others are forgotten, the files start declaring different functions.

Header file

The declaration is written once, in a header file—a file of declarations that is included wherever they are needed. The file main.cpp includes it with the #include directive:

C++
#include <iostream>
#include "triple.h"

int main() {
    std::cout << triple(14) << '\n';  // 42
}

The #include directive puts the text of the header triple.h in its place, and that text is a single line—the declaration:

C++
int triple(int x);

The name of your own header goes in quotes, while a standard library header goes in angle brackets. A header is usually named after the .cpp file that holds the definitions. The definition stays in triple.cpp, and that file includes triple.h too:

C++
#include "triple.h"

int triple(int x) {
    return x * 3;
}

Now the declaration and the definition sit in one file. If their return types differ, the compiler reports an error as soon as it compiles triple.cpp.

Translation unit

A translation unit is what the compiler translates: a .cpp file together with all the text its #include directives inserted. It compiles each unit separately, into an object file of its own. A header is never compiled by itself: its text becomes part of every unit that includes it. That is why a build command lists only .cpp files: clang++ main.cpp triple.cpp.

This splits a program into parts: the header says which functions exist, and the .cpp file says how they work. Any number of files in the program can include the header. The declaration is now written in one place, and the compiler checks every call against it.

Common mistake

A header of your own is included in angle brackets:

C++
#include <iostream>
#include <triple.h>  // ✗

int main() {
    std::cout << triple(14) << '\n';
}
TEXT
error: 'triple.h' file not found with <angled> include; use "quotes" instead

This is a compile error. With angle brackets, the compiler looks for the header among the library directories and does not search the folder that holds main.cpp. With quotes, the search starts in the file's own folder.