#include Directive

Of the preprocessor directives, probably the most important (and the most misleading) in modern C and C++ is the #include directive. The directive

#include "path/filename"

or

#include <path/filename>

...will cause the text of filename to be inserted into the source stream at the point where the directive occurs. For example, given the file foo.h,

/* foo.h */

extern int bar;

float foo();

which is then used in file foo.c

/* foo.c */

float baz = 3;

#include "foo.h"

int bar = 10;

float foo()
{
  return bar * baz; /* multiply the current values of bar and baz */ 
}

the preprocessor would produce:

float baz = 3;

extern int bar;

float foo();

int bar = 10;

float foo()
{
   return bar * baz;
} 

(Note that this omits any added whitespace and compiler-specific information which the preprocessor may generate.)

By long-standing convention, this is used almost exclusively to include header files, which are source files containing only constant definitions, type and class definitions, external variable references, and function prototypes which are to be shared between two or more source files. Generally speaking, actual variable declarations and function definitions are not put into header files, as this can lead to redeclaration errors when linking the resulting object files.

In C, header files are usually given the extension .h; while this convention used to be followed in C++, the newer C++ standard eliminates the extension entirely for the standard headers, and the C headers when used in C++ have the letter 'c' preprepended to the header name (i.e., <stdio.h> becomes <cstdio>). Some early C++ compilers used alternate extensions such as .hpp, .hxx, or .H (in systems where case is significant) in order to differentiate the C++ headers from the C headers, but this practice has largely been abandoned.

The locations where the preprocessor searches for the header files is determined by how the path is demarked; if the file path is in angle brackets, then the preprocessor searches the compiler-defined library paths, whereas if it is in double quotes, then it searches the paths given to the compiler by the user.

It is possible for header files to include other header files themselves. However, since this can lead to compile-time redefinition errors (as opposed to the link-time errors they are partly meant to avoid), most headers use either conditional compilation (see below) to ensure that they are only defined once. Some preprocessors allow the pragma

#pragma once

instead, but as with all pragmas, this is compiler-specific (see below).


Contents Previous Next