Advertisement
Beginner C++, Preprocessor & Macros

What is an include guard and why is it needed?

Short answer

An include guard prevents a header's contents from being included more than once in a translation unit, which would cause redefinition errors. It uses #ifndef/#define/#endif around the header body, or the non-standard-but-widely-supported #pragma once.

Save C++ mock interview
Advertisement
AModel answer
An include guard prevents a header's contents from being included more than once in a translation unit, which would cause redefinition errors. It uses #ifndef/#define/#endif around the header body, or the non-standard-but-widely-supported #pragma once. Guards are essential because headers are often included transitively multiple times.
#ifndef MYHEADER_H
#define MYHEADER_H
// ... declarations ...
#endif
Real-world example
Without an include guard, a widely-included header causes 'redefinition' errors when pulled in twice.
Likely follow-ups
  • What does #pragma once do? | Why can a header be included multiple times?
Related topics