Main Content

MISRA C:2012 Rule 20.1

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

Description

Rule Definition

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

Rationale

For better code readability, group all #include directives in a file at the top of the source file. Undefined behavior can occur if you use #include to include a standard header file within a declaration or definition or if you use part of the Standard Library before including the related standard header files.

Polyspace Implementation

Polyspace® flags text that precedes an #include directive. Polyspace ignores preprocessor directives, comments, spaces, or new line characters. Polyspace also ignores code that is hidden by using conditional compilation directives such as #if or #ifdef.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#if DEBUG

assert(0); 

#endif

#include<stdlib> //Compliant


int x;

#include <conio> //Noncompliant

In this example, the first #include statement is preceded by an assert statement. Because the assert statement is hidden by the #if condition, Polyspace does not flag the #include statement. The second #include statement follows a variable declaration that is not hidden. Polyspace flags the second #include statement.

Check Information

Group: Preprocessing Directives
Category: Advisory
AGC Category: Advisory

Version History

expand all