Many programming languages and other computer files have a directive, often called include
(as well as copy
and import
), that causes the contents of a second file to be inserted into the original file. These included files are called copybooks or header files. They are often used to define the physical layout of program data, pieces of procedural code and/or forward declarations while promoting encapsulation and the reuse of code.
The include directive allows libraries of code to be developed which help to:
An example situation which benefits from the use of an include directive is when referring to functions in a different file. Suppose we have a function add
in one file, which is then declared (with a function prototype) and then referred to in a second source file as follows:
One drawback of this method is that the prototype must be present in all files that use the function. Another drawback is that if the return type or arguments of the function are changed, these prototypes will have to be updated. Putting the prototype in a single, separate file avoids these problems. Assuming the prototype is moved to the file add.h
, the second source file can then become:
Now, every time the code is compiled, the latest function prototypes in add.h
will be included in the files using them, avoiding potentially disastrous errors.
In C and C++, the #include
preprocessor directive causes the compiler to replace that line with the entire text of the contents of the named source file (if included in quotes: "") or named header (if included in angle brackets: <>); note that a header need not be a file. Inclusion continues recursively on these included contents, up to an implementation-defined nesting limit. Headers need not have names corresponding to files: in C++ standard headers are typically identified with words, like "vector", hence #include <vector>
while in C standard headers have identifiers in the form of filenames with a ".h" extension, as in #include <stdio.h>
. A "source file" can be any file, with a name of any form, but is most commonly named with a ".h" extension and called a "header file" (sometimes ".hpp" or ".hh" to distinguish C++ headers), though files with .c, .cc, and .cpp extensions may also be included (particularly in the Single Compilation Unit technique), and sometimes other extensions are used.