静态代码检查工具 cppcheck 的使用

      CppCheck是一个C/C++代码缺陷静态检查工具。不同于C/C++编译器及其他分析工具,CppCheck仅仅检查编译器检查不出来的bug,不检查语法错误。所谓静态代码检查就是使用一个工具检查我们写的代码是否安全和健壮,是否有隐藏的问题。

比方无意间写了这种代码: 

int n = 10;
char* buffer = new char[n];
buffer[n] = 0;


这全然是符合语法规范的,可是静态代码检查工具会提示此处会溢出。也就是说,它是一个更加严格的编译器。使用比較广泛的C/C++静态代码检查工具有cppcheck    pc-lint等。pc-lint是资格最老,最强力的代码检查工具,可是是收费软件,而且配置起来有一点点麻烦。

CppCheck 是免费的开源软件。使用起来也非常方便。 

http://cppcheck.sourceforge.net/   下载最新的cppcheck。

使用方式:

一、GUI方式:安装完就能够使用里面的cppcheck-gui来检測代码。界面例如以下:

二、命令行方式:

三、集成到IDE开发环境中使用:

1、VS

參考这里(http://avitebskiy.blogspot.tw/2012/10/poor-mans-visual-studio-cppcheck.html),能够方便的把cppcheck嵌入到vs,然后能够方便的对一个文件进行检查,并且支持错误跳转。

  • click the Add button
  • set the Title, for example Cppcheck
  • set Command to C:Program Files (x86)Cppcheckcppcheck.exe
  • set Arguments to --quiet --verbose --template=vs $(ItemPath)
  • set Initial Directory to $(ItemDir)
  • make sure Use Output window checkbox is enabled
  • click on the Move Up button repeatedly until your entry is at the top of the list, this will make it easier to identify you new command as you can count on it being calledTools.ExternalCommand1
  • click OK.

2、Qt Creator

     在QtCreator中点击:tools=>external=>config...=>add 弹出例如以下对话框:

填入下列參数:

设置完后就能够用cppcheck检查指定文件夹下的代码文件:tools=>external=>cppcheck 開始检查。

參考文章: http://www.cnblogs.com/lancidie/archive/2013/04/13/3019505.html

下面这篇文章也很具体:http://blog.csdn.net/akof1314/article/details/7477014

原文地址:https://www.cnblogs.com/zfyouxi/p/4484255.html