C++ › Preprocessor & Macros

What is an include guard and why is it needed?

Beginner

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.

Common follow-ups: What does #pragma once do? | Why can a header be included multiple times?