1. cppcheck工具说明:
cppcheck工具是一个C/C++代码缺陷静态检查工具。它不仅可以检查代码中的语法错误,还可以检查出编译器检查不出来的缺陷,从而辅助提升代码质量。
2. Linux下cppcheck工具安装:Linux终端输入:sudo apt-get install cppcheck
3. cppcheck工具使用:
(1) 如对文件进行代码检查,只需要如下操作即可:
cppcheck [filename]
(2) 如对目录中所有代码进行检查,只需要如下操作即可:
cppcheck [path]
使用示例如下所示:
对C源文件进行检查如下:
对目录中所有C源文件进行检查如下:
4. cppcheck工具检查代码问题包括如下:
- 野指针。
- 整型变量溢出。
- 无效的移位操作数。
- 无效的转换。
- 无效使用STL库。
- 内存泄漏检测。
- 代码格式错误以及性能原因检查。
5. 默认情况下只显示错误信息,可以通过“--enable”命令来启动更多检查,可用命令如下:
--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
5. cppcheck可以指定编译器(--std=<id>)
指定编译器版本,参数id:c89、c99、c11、c++03、c++11、c++14、c++17、c++20。例如:
cppcheck --std=c99 ./path
6. cppcheck还可以设置输出格式,如下所示:
cppcheck --template=vs path (Visual Studio兼容模式)
cppcheck --template=gcc path (Gcc兼容模式)
cppcheck --template={"{file},{line},{severity},{id},{message}"} (自定义模式)
cppcheck也可设置规则忽略一些目录或错误,以及根据配置文件检查函数参数,格式化输出等功能。可参考官方文档。