Include Guards

Include guards are used to prevent the contents of a file from being included more than once.

Example, bigint.hpp:

#ifndef CS2_BIGINT_HPP
#define CS2_BIGINT_HPP
 
class bigint
{
  // ...
};
 
#endif

The header file above has an include guard. The #ifndef is an if statement. The #endif is the end of the if body. The ndef in the if means not defined.

If CS2_BIGINT_HPP is defined as the preprocessor reads the file and the condition is false, the if body is skipped.

If CS2_BIGINT_HPP is not defined as the preprocessor reads the file and the condition is true, then the body of the if is processed. If another file tries to include the CS2_BIGINT_HPP file again, the condition will be false and the if body is skipped.

CS2_BIGINT_HPP is just a name and is usually derived from the header file's name. We normally use the file name with underscores between and ending (CAPITAL_SNAKE_CASE).

NEVER use a leading underscore. This is reserved for the standard library, e.g., _STRING_HPP_.

Golden rule of C++: ALWAYS have include guards for EVERY header file.

For some examples, you can look at the C++ header files in the directory /usr/include/c++/<version> (replace <version> with the most recent version number).


URL: https://data-structures.cs.kent.edu/labs/Info/include_guard.html
Last update: EST