主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

MISRA C:2012 Rule 20.1

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

描述

规则定义

#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 类别:建议

版本历史记录

全部展开


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.