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.)
Figure 6.4.2. including library.h into main.cpp and library.cpp means that the code from it is added to both files as they are individually compiled.
Doing this ensures that when the compiler hits the call to the doubleValue function on line 10, it has already seen the declaration for that function from the included library.h file.
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.
Always use " " around the filename for files you create.
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.

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.