Interview Q&A · C++ · 10 questions in this topic

Compilation, Linking & ODR — C++ Interview Q&A

All C++ topics

The build model interviewers love — translation units, headers, include guards, linkage, ODR and static vs dynamic libraries. Part of Compilation, Linking & ODR · 213 questions in the C++ bank.

What is a translation unit?

Answer

A translation unit is one source file after preprocessing (all #includes expanded, macros processed) — the actual input the compiler translates. Each .cpp typically forms one TU; headers are fragments pasted into TUs, never compiled alone.

One-definition and linkage rules operate per-TU and across TUs, which is why the same header included twice needs guards.

Example

Example.cppcpp
// main.cpp includes <vector> + "widget.h" → one TU
// widget.cpp includes "widget.h" → another TU
// the linker joins their object files

What is the One Definition Rule (ODR)?

Answer

Across the program, each non-inline function, variable, class and enum has exactly one definition (inline variables/functions and templates may repeat identically per TU). Within a TU, no entity may be defined twice. Violations may link silently with merged duplicates (inline) or fail — or worse, exhibit UB from differing definitions.

Headers carry declarations; definitions live in one .cpp unless inline/template.

Example

Example.cppcpp
// widget.h: declaration
void paint();
// widget.cpp: single definition
void paint() {}

What are include guards and what is `#pragma once`?

Answer

Both prevent double inclusion within one TU: classic guards use #ifndef/#define/#endif around the header; #pragma once is the shorter compiler-supported equivalent. Guards protect against diamond includes and self-inclusion.

#pragma once is universally supported and simpler, but non-standard (still fine in practice); guards are standard and work everywhere including exotic filesystems.

Example

Example.cppcpp
// widget.h
#pragma once
// ...or standard guards:
// #ifndef WIDGET_H
// #define WIDGET_H
// ...
// #endif

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits