Main Content

MISRA C++:2023 Rule 19.0.3

#include directives should only be preceded by preprocessor directives or comments

Since R2024b

Description

Rule Definition

#include directives should only be preceded by preprocessor directives or comments.

Rationale

Grouping all #include preprocessor directives at the beginning of the source file makes the code more readable. #include directives might include header files where macros are defined. If you use such a macro before including its definition, you might encounter unexpected code behavior.

Polyspace Implementation

Polyspace® reports violations of this rule when an #include directive comes after any code that is not a comment, preprocessor directive, or language specification token. Polyspace ignores code that is hidden by using conditional compilation directives such as #if or #ifdef. Polyspace does not report a violation of this rule when an #include directive is located within an extern "C" block.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

//this comment is compliant     //Compliant
/*
    This comment is compliant
*/

#ifndef TESTING_H               //Compliant
#define TESTING_H               //Compliant

#include <iostream>             //Compliant	
using namespace std;            //Compliant
#include <exception>            //Noncompliant

#endif

Because an include directive follows a code statement that is neither a preprocessor directive nor a comment, Polyspace flags the include directive.

Check Information

Group: Preprocessing Directives
Category: Advisory

Version History

Introduced in R2024b