首页 > 解决方案 > How to make C code to MISRA C:2012 compliance?

问题描述

I am validating MISRA C:2012 standard to my MCU code using PC-Lint. I got following errors.Here I posted a sample code where I got errors on condition statements.

1] unsigned integer literal without a 'U' suffix [MISRA 2012 Rule 7.2, required] S_LCB_100,

2] side effects on right hand of logical operator, '&&' [MISRA 2012 Rule 13.5, required] while(( 0x00000000 != List[Loop] ) && ( 0 != Counter ))

3] : a signed value and an unsigned value cannot be used together as operands to != [MISRA 2012 Rule 10.4, required] while(( 0x00000000 != List[Loop] ) && ( 0 != Counter ))

4] : a signed value and an unsigned value cannot be used together as operands to != [MISRA 2012 Rule 10.4, required] while(( 0x00000000 != List[Loop] ) && ( 0 != Counter ))

5] an unsigned value and a signed value cannot be used together as operands to == [MISRA 2012 Rule 10.4, required] if ( List[Loop] == 0x00000000 )

How can I make it MISRA C:2012 compliance?

typedef unsigned char UINT8;
typedef unsigned char BYTE;  
typedef unsigned long int UINT32; 
#define S_LCB_100 0xF0BB12DE;
#define MULTI 0x1A;
volatile static BYTE Counter = 0;
static UINT8 Loop = 0;    
static UINT32 List[]=  
{
    S_LCB_100,
    0x00000000,
};
while(( 0x00000000 != List[Loop] ) && ( 0 != Counter ))
{
 .......some code
}
if ( List[Loop] == 0x00000000 )
{
.....some code
} 

标签: cembeddedmisra

解决方案


一般说明:

  • 在担心 MISRA-C 合规性之前,让代码在 C 编译器上编译。
  • 然后确保您有可用的 MISRA-C:2012 文档,否则您根本无法使用 MISRA。
  • 摆脱诸如“尤达条件”之类的废话。
  • 摆脱自定义 typedef 并使用stdint.h. 如果您在 C90 上,则typedef使用stdint.h.

1] 不带“U”后缀的无符号整数文字 [MISRA 2012 规则 7.2,必需] S_LCB_100,

很不言自明。将U或添加u到应该是无符号的整数常量。阅读规则 7.2 了解详情。

2] 逻辑运算符右侧的副作用 '&&' [MISRA 2012 规则 13.5,必需] while(( 0x00000000 != List[Loop] ) && ( 0 != Counter ))

Counter具有挥发性,访问它是一种副作用。所以它通常不应该存在于复杂的表达式中,特别是不应该存在于布尔 && 表达式的右侧——这是非常有问题的代码。在这种情况下,您可以简单地将代码重写为:

uint32_t count = (uint32_t)Counter;

while((count != 0u) && (List[Loop] != 0u))
{
  ...
  count = (uint32_t)Counter; // read volatile variable in an expression of its own
}

3] 有符号值和无符号值不能一起用作 != [MISRA 2012 规则 10.4,必需] while(( 0x00000000 != List[Loop] ) && ( 0 != Counter )) 的操作数

这是因为Counter被声明为BYTE. 删除所有此类自制的废话类型并将其声明为uint8_t。然后使用while如上所示的表格。使用u后缀。这应该修复 2) 到 5)。


推荐阅读