主要内容

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

MISRA C:2012 Rule 8.8

The static storage class specifier shall be used in all declarations of objects and functions that have internal linkage

描述

规则定义

The static storage class specifier shall be used in all declarations of objects and functions that have internal linkage 1 .

理由

如果未在所有具有内部链接的对象声明中一致地使用 static 指定符,则可能会声明具有外部和内部链接的相同对象。

在此情况下,链接遵循之前可见的规范(C99 标准,第 6.2.2 节)。例如,如果先前的说明指明内部链接,则即使后面的说明指明外部链接,该对象也有内部链接。如果您只注意到后面的规格,您可能会得到不同的结果。

Polyspace 实现

此规则检查项检测下列情形:

  • 使用不同的存储指定符多次声明了相同的对象。

  • 使用不同的存储指定符声明和定义了相同的函数。

故障排除

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

示例

全部展开

static int foo = 0;
extern int foo;         /* Non-compliant */

extern int hhh;
static int hhh;         /* Non-compliant */

在此示例中,第一行定义了具有内部链接的 foo。第一行是合规的,因为示例使用了关键字 static。第二行在声明中未使用 static,因此该声明不合规。相比之下,第三行使用关键字 extern 声明 hhh,创建外部链接。第四行声明了具有内部链接的 hhh,但该声明与第一个 hhh 声明冲突。

更正 - 保持 staticextern 的一致性

一种可能的更正是始终使用 staticextern

static int foo = 0;
static int foo;

extern int hhh;
extern int hhh;
static int fee(void);  /* Compliant - declaration: internal linkage */
int fee(void){         /* Non-compliant */
  return 1;
}

static int ggg(int);  /* Compliant - declaration: internal linkage */
extern int ggg(int x){  /* Non-compliant */
  return 1 + x;
}

此示例显示了两个内部链接违规。由于 feeggg 具有内部链接,因此必须在定义中使用 static 类指定符才能与 MISRA™ 合规。

检查信息

组:声明和定义
类别:必需
AGC 类别:必需

版本历史记录

在 R2014b 中推出


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.