What are the dangers of macros affecting names and how do you mitigate them?
Short 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.
Advertisement
AModel 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.hReal-world example
windows.h's min/max macros break std::min until NOMINMAX is defined, a classic macro-name collision.
Likely follow-ups
- Why do macros ignore scope? | How do you prevent macro name clashes?
Related topics