linuxcppcheck静态代码检查md

5次阅读

共计 1528 个字符,预计需要花费 4 分钟才能阅读完成。

简介

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

正文完
 0