Why is this an issue?
While it is legal to place #define
and #undef
directives anywhere in a source file, placing them outside of the global
namespace is misleading since their scope is not actually restricted. This may be inconsistent with developer expectations.
Noncompliant code example
namespace NS
{
#ifndef MY_HDR
#define MY_HDR /* Noncompliant */
#undef FOO /* Noncompliant */
#endif
}
Compliant solution
#ifndef MY_HDR
#define MY_HDR
#undef FOO
#endif
Resources
- MISRA C:2004, 19.5 - Macros shall not be #define’d or #undef’d within a block.
- MISRA C++:2008, 16-0-2 - Macros shall only be #define’d or #undef’d in the global namespace.