Single Inclusion of Files

This page was translated by a robot.

Since nesting can result in a header file being included more than once by the preprocessor, a mechanism must exist so that the definitions it contains are not compiled twice, which would result in Already defined or Redefinition of errors. This is usually solved with the following construct:

#ifndef NAME_OF_FILE_INCLUDED
#define NAME_OF_FILE_INCLUDED

// Code

#endif //NAME_OF_FILE_INCLUDED

Details

This construct embeds the actual code in a conditional compilation. The condition for compilation is met if the macro used has not yet been defined. When this construct is compiled for the first time, this condition is met and the macro is defined immediately. It is usually defined without an assignment, but it can also be assigned a value. This is irrelevant for this construct, since the existence of the macro is only checked for. The next time this file is compiled, the macro will be defined and all definitions will be skipped.

The name of the constant is arbitrary, but according to general knowledge it reflects the contents of the file, which is often achieved using the file name. Some automatic tools often add a unique number to this constant to eliminate any possibility that the macro has already been defined somewhere else. The additional comment on the #endifline is optional but is seen frequently.

#pragmaThe directive can also be used with some compilers as a solution to this problem , but it is not valid for every compiler and is therefore not recommended. The Objective-C language has added the #import directive specifically for this problem , which, however, has no place in C++ programs.

Instead of the #ifndefdirective in the first line, you can also write the following line:

#if !defined NAME_OF_FILE_INCLUDED
#define NAME_OF_FILE_INCLUDED

// Code

#endif //NAME_OF_FILE_INCLUDED

However, the use of the definedoperator with this construct is not very common, if only for reasons of readability.

The attempt to define the whole construct itself as a macro fails, since macros cannot contain directives. In addition, everyone understands the above examples, whereas an own construction must first be looked up.