This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 19.0.4 - #undef should only be used for macros defined previously in the same file
[cpp.predefined] Undefined 4
Category: Advisory
Analysis: Decidable,Single Translation Unit
Rationale
Since macros are not subject to the usual scoping rules of the language, complex use of #undef can lead to confusion with respect to
the existence or meaning of a macro when it is used in the code. However, it might be desirable to limit the number of active macros at any point in
the code to help prevent inappropriate use; if a macro is only required for a specific purpose, a common idiom is to #define it, use it
and #undef it immediately afterwards.
Permitting #undef to be used for macros that are defined in the same file enables the scope of those macros to be restricted whilst
preventing complex uses that could lead to confusion.
Note: undefining a macro defined by the C++ Standard Library can result in undefined behaviour.
Example
// File.cpp
#include "A.h" // This header defines the macro M
#undef M // Non-compliant - defined in another file
#define ID( name ) constexpr auto name = #name
ID( IdA );
ID( IdB );
#undef ID // Compliant - defined in this file
Copyright The MISRA Consortium Limited © 2023