Interview Q&A · C · 12 questions in this topic
Preprocessor, Headers & Linking — C Interview Q&A
The build model interviewers love — macros done right, include guards, linkage, and static vs dynamic libraries. Part of Preprocessor & Build · 202 questions in the C bank.
What does the preprocessor do? What are the common directives?
Answer
#include pastes files, #define creates macros, #ifdef/#ifndef/#if/#elif/#else/#endif select code conditionally, #error aborts with a message, #pragma issues compiler hints, #line renumbers diagnostics. It runs before compilation as pure textual transformation with no C understanding.
Because it is textual, every macro bug is a substitution surprise — parenthesize and prefer language features where possible.
Example
#ifdef DEBUG #define LOG(x) printf("DBG: %s\n", x) #else #define LOG(x) ((void)0) #endif
How do you write safe function-like macros?
Answer
Parenthesize every parameter use and the whole body (precedence), wrap multi-statement macros in do { ... } while (0) (semicolon safety), avoid evaluating arguments twice (side-effect duplication), and prefer static inline functions, enums and consts where possible.
The do-while-0 wrapper makes the macro behave like one statement in if/else chains — without it, trailing else binds wrongly.
Example
#define MAX(a, b) ((a) > (b) ? (a) : (b)) /* parens everywhere */ #define LOG_HI() do { puts("hi"); } while (0) /* one-statement shape */
What are the `#` (stringize) and `##` (token-paste) operators?
Answer
# turns a macro argument into a string literal (#x becomes "x") — used for assertions and generated messages. ## concatenates tokens (a##b becomes ab) — used for generated identifiers and accessor families.
Both operate at expansion time on tokens, not values; overuse creates undebuggable identifier soup, so confine them to small, documented generator macros.
Example
#define STR(x) #x /* STR(hi) -> "hi" */ #define FIELD(t, n) t n; /* generator building blocks */ #define CAT(a, b) a##b /* CAT(var, 1) -> var1 */
What are include guards and `#pragma once`? What breaks without them?
Answer
Both prevent double inclusion within one translation unit: classic guards use #ifndef/#define/#endif; #pragma once is the shorter compiler-supported equivalent. Without them, diamond includes redefine types and variables — breaking the build, or worse, silently duplicating definitions.
#pragma once is universally supported and simpler; guards are standard and work everywhere including exotic filesystems.
Example
/* sensor.h */ #ifndef SENSOR_H #define SENSOR_H /* ... declarations ... */ #endif /* or simply: #pragma once */
What should a header contain vs a source file?
Answer
Headers: declarations, macro definitions, type definitions, static inline functions, extern declarations. Source files: non-inline function definitions, data definitions, TU-local helpers. Headers must be self-contained (compile alone) and minimal (forward-declare structs where full definitions are unneeded).
Self-containment plus minimal includes keeps builds fast and ODR-clean.
Example
/* widget.h: interface only */ #ifndef WIDGET_H #define WIDGET_H typedef struct widget widget_t; widget_t *widget_open(int id); void widget_close(widget_t *w); #endif
What do `extern`, internal linkage and static functions control?
Answer
extern declares without defining (cross-TU variables/functions). File-static restricts to internal linkage — private to its .c file. Functions default to external linkage; data too unless static.
The module pattern: static everything by default, expose only the API — the linker then enforces your encapsulation.
Example
/* shared.c: int shared_counter = 0; // external linkage */ /* user.c: extern int shared_counter; // declaration only */ static int helper(void) { return 1; } /* TU-local */
💡 extern declares, static hides — the linkage duo in one line.
What is the One Definition Rule equivalent in C (and what happens on violation)?
Answer
C has no single ODR clause, but the effect is identical: each object/function has exactly one external definition across the program (inline and tentative-definition corner cases aside). Violations fail at link time (multiple definition) — or worse, silently merge differing tentative definitions into UB.
Headers declare; exactly one .c file defines. -fno-common (now default) closed the old merging loophole.
Example
/* widget.h: extern int state; // declaration */ /* widget.c: int state = 0; // single definition */
What is the difference between static and dynamic linking?
Answer
Static linking copies library code into the executable: single file, no runtime dependency, larger binary, updates require relinking. Dynamic linking references shared libraries loaded at startup: smaller binaries, shared memory, independent updates — at the cost of load time, versioning pain and deployment complexity.
Static suits self-contained tools and embedded targets; dynamic suits system libraries.
Key points
- 1Static (.a) — baked in at link time.
- 2Dynamic (.so/.dll) — resolved at load/run time.
- 3Trade-off — hermeticity vs sharing and updatability.
What is name mangling, and does C have it?
Answer
C does not mangle: symbol names pass through nearly unchanged (sometimes with a leading underscore), which is why C ABIs are the universal interop language. C++ mangles overloaded names into unique symbols — extern "C" disables that for cross-language boundaries.
Practical fallout: demangle with c++filt when reading C++ linker errors; plain nm suffices for C.
Example
/* nm libsensor.a | grep read_sensor // readable C symbols */ /* c++filt _ZN1S3addEii -> S::add(int, int) */
How do you create and use static vs shared libraries?
Answer
Static: compile with -c, archive with ar rcs libfoo.a, link normally — code is copied in. Shared: compile with -fPIC, link with -shared into libfoo.so, link with -L/-lfoo and ensure runtime discovery (rpath, LD_LIBRARY_PATH, system dirs).
Shared libraries need versioned SONAMEs and symbol-visibility discipline (-fvisibility=hidden plus explicit exports) to keep ABIs stable.
Example
/* gcc -c sensor.c -o sensor.o */ /* ar rcs libsensor.a sensor.o // static */ /* gcc -fPIC -shared sensor.c -o libsensor.so // shared */
💡 Position-independent code (-fPIC) is the shared-library prerequisite to name-drop.
What is conditional compilation for (platforms, features, debug)?
Answer
#ifdef/_WIN32/__linux__ select platform code; feature macros (HAVE_FOO from configure/CMake) gate optional dependencies; NDEBUG strips asserts for release; DEBUG/verbose flags gate tracing. Generated config.h files feed detected capabilities into the build.
Keep conditional code small and symmetric (both branches compile in CI) — untested #else branches rot.
Example
#ifdef _WIN32 /* Sleep(ms); */ #else /* usleep(ms * 1000); */ #endif #ifndef NDEBUG /* extra validation */ #endif
How do you reduce C build times?
Answer
Cut work per TU (forward-declare structs, lean headers, precompiled headers), cut redundant work (ccache), and parallelize (make -j, ninja, distcc). Measure with -ftime-trace equivalents or build profilers to see whether headers, optimization or linking dominate.
Forward declarations of struct types (no include needed for pointers) are the highest-leverage C habit.
Key points
- 1Less input — forward declarations, lean/PCH headers.
- 2Less repeat — ccache, unity builds for cold compiles.
- 3More parallelism — jobs, distributed builds, fast linkers.
💡 Forward-declare plus measure-first is the credible senior answer.
Recommended resourcesAffiliate links · may earn us a commission