What are #ifndef and #define used for in C++?

#ifndef and #define are known as header guards. Their primary purpose is to prevent C++ header files from being included multiple times.

svg viewer

Example​

Consider a sample header file which uses these guards:

#ifndef HEADERFILE_H
#define HEADERFILE_H
// some declarations in
// the header file.
#endif

Explanation

When the code is compiled, the preprocessor checks whether HEADERFILE_H has been previously defined. If this is the first time we have included the header, HEADERFILE_H will not have been defined. Consequently, the compiler defines HEADERFILE_H and includes the contents of the file.

If the header is included again into the same file, HEADERFILE_H will already have been defined from the first time that the contents of the header were included; the ifndef guard will then ensure that the contents of the header will be ignored.

These header guards prevent redeclaration of any identifiers such as types, enums, classes, and static variables. They also prevent recursive inclusions; for example, a case where “file1.h” includes “file2.h” and “file2.h” includes “file1.h”.

Copyright ©2024 Educative, Inc. All rights reserved