Skip to main content

Section 6.4 Using Header Files

A header file is not compiled directly. Instead, the whole point is for .cpp files to include the .h file it using the #include directive:
Listing 6.4.1. main.cpp (with include)
When the compiler is working on main.cpp, it will see the #include "library.h" directive and read the contents of library.h into that location. (Including a file essentially copies the contents of that file into the including file.) This means that the compiler will know about the doubleValue function and be able to compile the code in main.cpp that calls it.
Note that this use of include uses " " around the name of the file to include instead of < >. The angle brackets say β€œthis is a standard library, look for it with the compiler’s file”. The quotes say β€œthis is a library that is NOT part of the standard compiler libraries, look for it in our files”. We use #include <iostream> because iostream is a standard library. Our library.h file is not.

Warning 6.4.1.

If you use the wrong symbols around the filename in your include, the compiler may not find the file because it is looking in the wrong folder.
The compiler does not need to be told to build the header (as it is included into the .cpp files that need it to build). So our recipe to build a program code would make no mention of the header file:
$ g++ main.cpp library.cpp -o program.exe
Generally, a .cpp file will include it’s own .h - we would put #include "library.h" in the library.cpp file as well as the main file. This means that the code from the header file would be used as part of compiling both .cpp files. This is why the header can only contain declarations, not definitions. We need to make sure that we do not have two copies of any function’s definition.
Figure 6.4.2. Compiling main.cpp and library.cpp files that each include library.h.

Note 6.4.2.

Making a .cpp/.h file pair for the code and header is the most common way to build a code library in C++. However, the code in this book does not use the header file strategy in order to minimize the number of β€œfiles” that need to be defined in the text. Instead, we will rely on modules, which are discussed next.

Checkpoint 6.4.1.

Which is the true statements?
  • Including a header essentially copies its contents into the location of the #include directive.
  • Multiple .cpp files can include the same header file.
  • The .h file must be added to the compiler command.
  • Include directives for files you create should use angle brackets around the file name (< >).
You have attempted of activities on this page.