File Inclusion

File inclusion is a feature of the C++ preprocessor that allows a source code file to use shared code. We consider shared code to be classes or functions declared in other files. In C++, we can only access a shared class or function by including its declaration into our program. This must be done since C++, unlike Java, shares code textually. Imagine having to include manually the declaration for every function and class used in a program. That would be quite a cumbersome task. Luckily, the preprocessor automates this through file inclusion.

A programmer issues the #include preprocessor directive to instruct the preprocessor to perform file inclusion. This directive takes a file or library name as a parameter. When processing an #include directive, the preprocessor replaces the line containing the directive with the contents of the file that the directive specifies. Listing 1 demonstrates file inclusion.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: #include <string>#include <cstdlib>#include <iostream>#include <fstream> #include "my_functions.h"#include "my_class.h" #include "..another_file1.h"#include "directorysubanother_file2.h" using namespace std; int main(int argc, char* argv[]) { // Rest of program...
Listing 1 The #include directive

The #include directive accepts two different forms of its parameter. The above example demonstrates use of the first form in lines 1 through 4. In this form, angle brackets surround the parameter in the #include directive. This signifies that the preprocessor should search for the specified file in an implementation dependent set of places. Typically, this set of places includes system and library directories. Double quotes surround the parameter in the second form of the #include directive. In this form, the #include directive instructs the preprocessor to look for the specified file in the same directory where the file being preprocessed exists. Lines 6 through 10 of Listing 1 illustrate this form of the directive. C++ programmers typically use the first form to include libraries and the second form to include files they have created.