C Programming · Interview question

What is an include guard and what problem does it solve?

A strong answer

An include guard is the #ifndef X_H / #define X_H / ... / #endif wrapper around a header's contents. Because #include literally pastes a header's text into each file that includes it, and headers often include other headers, the same header can be textually included multiple times in one translation unit, causing "redefinition" errors for its typedefs, structs, and macros. The guard makes the first inclusion define the guard macro and process the body; every subsequent inclusion sees the macro already defined and skips the entire file. #pragma once is a widely supported non-standard alternative that's simpler and avoids guard-name collisions, but the #ifndef form is universally portable. Either way, every header should have one.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

The Preprocessor

Text substitution before the compiler ever runs: object and function macros, header guards, conditional compilation, and why a naive MAX macro evaluates its argument twice.

More The Preprocessor questions

Browse all 472 interview questions
What is an include guard and what problem does it solve? | EmbeddedPrep.io