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.1.2 - All #else, #elif and #endif preprocessor directives shall reside in the same file as the
#if, #ifdef or #ifndef directive to which they are related
Category: Required
Analysis: Decidable,Single Translation Unit
Rationale
Confusion can arise when code blocks are included or excluded by the use of conditional compilation directives which are spread over multiple
files. Requiring that a #if directive be terminated within the same file reduces the visual complexity of the code and the chance that
errors will be made during maintenance.
Notes:
-
#if directives may be used within included files, provided they are terminated within the same file.
- It is not clear from the C++ Standard whether such constructs are allowed or not. Some compilers do require that a
#endif (etc.)
must be in the same file as the associated #if (etc.), and all compilers tested raise an error if this is not the case. However, this
requirement is not explicitly expressed in the C++ Standard, and there is a reading of the grammar that would allow it. This rule aims to prevent
this construct, should any compiler actually allow it.
Example
// file1.c
#ifdef A // Compliant
#include "file1.h"
#endif
// End of file1.c
// file1.h
#if 1 // Compliant
#endif
// End of file1.h
// file2.c
#if 1 // Non-compliant
#include "file2.h"
// End of file2.c
// file2.h
#endif
// End of file2.h
Copyright The MISRA Consortium Limited © 2023