Advertisement
Intermediate C++, Compilation & Linking

Why do you need include guards or #pragma once, in linkage terms?

Short answer

Headers are textually included into every translation unit that uses them, potentially multiple times via transitive includes. Without guards, a header's declarations/definitions would be duplicated within one translation unit, causing redefinition compile errors.

Save C++ mock interview
Advertisement
AModel answer
Headers are textually included into every translation unit that uses them, potentially multiple times via transitive includes. Without guards, a header's declarations/definitions would be duplicated within one translation unit, causing redefinition compile errors. Guards ensure the header's contents appear once per translation unit, complementing the ODR across translation units.
Real-world example
An unguarded header included twice in one .cpp triggers 'redefinition' errors the guard prevents.
Likely follow-ups
  • What duplication do guards prevent? | How does this relate to the ODR?
Related topics