c - 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
}
解决方案
一般说明:
- 在担心 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)。
推荐阅读
- r - 如何使用复选框从 visNetwork 交互过滤节点/边?(使用 R 闪亮)
- c - 内核模块时间测量
- typescript - 使用 Rollup 从本地 Yarn 工作区捆绑 TypeScript 类型
- sql - SparkStatementException:“引用不明确
- java - graphql-spring-boot-starter 只有 websockets 的应用程序
- reactjs - 无法在 redux modal 中使用 hooks 来使用组件
- javascript - ReactJS:预期的属性速记对象速记
- woocommerce - 设置 wc 产品简短描述
- django - 在 dajngo CreateView 中自动添加归档
- python - 如何根据值以及python中的下一个和最后一个邻居选择列表中的项目