主要内容

MISRA C:2023 Rule 20.1

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

自 R2024a 起

描述

规则定义

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

理由

为了提高代码可读性,请将文件中的所有 #include 指令一起放在源文件的顶部。如果您在声明或定义中使用 #include 来包含标准头文件,或者在包含相关标准头文件之前使用标准库的部分内容,可能会发生未定义行为。

Polyspace 实现

Polyspace® 会标记出现在 #include 指令之前的文本。Polyspace 会忽略预处理器指令、注释、空格或换行符。Polyspace 还会忽略通过使用条件编译指令(例如 #if#ifdef)隐藏的代码。

故障排除

如果您预期会出现违规,但未看到该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

#if DEBUG

assert(0); 

#endif

#include<stdlib> //Compliant


int x;

#include <conio> //Noncompliant

在此示例中,第一个 #include 语句前面有一个 assert 语句。因为 assert 语句被 #if 条件隐藏了,所以Polyspace 不会标记这个 #include 语句。第二个 #include 语句紧跟在一个未被隐藏的变量声明之后。Polyspace 会标记第二个 #include 语句。

检查信息

组:预处理指令
类别:建议
AGC 类别:建议

版本历史记录

在 R2024a 中推出


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.