cppcheck java_linux-cppcheck静态代码检查.md

简介

cppcheck是一个C/C++的静态代码检查工具。它不仅可以检查代码中的语法错误,还可以检查出编译器检查不出来的缺陷,从而辅助提升代码质量。

cppcheck能够发现很多错误,但不能发现所有的错误。

简单说明

首先使用如下命令安装:

sudo apt install cppcheck

cppcheck支持的检测功能如下:

野指针。

整型变量溢出。

无效的移位操作数。

无效的转换。

无效使用STL库。

内存泄漏检测。

代码格式错误以及性能原因检查。

如对文件进行代码检查,只需要如下操作即可:

cppcheck [filename]

如对目录中所有代码进行检查,只需要如下操作即可:

cppcheck [path]

默认情况下只显示错误信息,可以通过“--enable”命令来启动更多检查,可用命令如下:

--enable=error #发现bug时提示级别

--enable=style #编码格式问题,未使用的函数、多余的代码等

--enable=portability #打开移植性警告,在其它平台上可能出现兼容性问题

--enable=warning #打开警告消息

--enable=performance #打开性能消息

--enable=information #打开信息消息

--enable=all #打开所有消息

使用示例:

# enable warning messages

cppcheck --enable=warning file.c

# enable performance messages

cppcheck --enable=performance file.c

# enable information messages

cppcheck --enable=information file.c

# For historical reasons, --enable=style enables warning, performance,

# portability and style messages. These are all reported as "style" when

# using the old xml format.

cppcheck --enable=style file.c

# enable warning and information messages

cppcheck --enable=warning,information file.c

# enable unusedFunction checking. This is not enabled by --enable=style

# because it doesn't work well on libraries.

cppcheck --enable=unusedFunction file.c

# enable all messages

cppcheck --enable=all

设置输出格式:

cppcheck --template=vs path (Visual Studio 兼容模式)

cppcheck --template=gcc path (Gcc兼容模式)

cppcheck --template={"{file},{line},{severity},{id},{message}"} (自定义模式)

使用代码示例

int main()

{

char a[10];

a[10] = 0;

return 0;

}

检查结果如下:

$ cppcheck demo1.c

Checking demo1.c ...

[demo1.c:4]: (error) Array 'a[10]' accessed at index 10, which is out of bounds.

cppcheck也可设置规则忽略一些目录或错误,以及根据配置文件检查函数参数,格式化输出等功能。可参考官方文档。

email: MingruiZhou@outlook.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值