Back to results for “Namespaces”
C++ › Preprocessor & Macros

What are the dangers of macros affecting names and how do you mitigate them?

Advanced

Answer

Because macros do global text replacement ignoring scope, a macro like #define max(...) can clobber legitimate identifiers (e.g., std::max, member functions), causing baffling errors. Mitigations: avoid macros where possible, use ALL_CAPS naming to signal macros, #undef them promptly, and be wary of platform headers (like windows.h) that define common names.
// windows.h defines min/max macros that break std::min/std::max
#define NOMINMAX   // before including windows.h
Real-world example windows.h's min/max macros break std::min until NOMINMAX is defined, a classic macro-name collision.

Common follow-ups: Why do macros ignore scope? | How do you prevent macro name clashes?