CppCheck静态代码检查工具教程【Windows和Linux端】
目录
1、背景
2、特性介绍
2.1、检查结果
2.2、检查范围
2.3、支持的检查规则(列举一些):
2.4、自定义规则
3、linux 端
4、windows 端
1、背景
最近调研了几款 c/c++ 代码静态检查工具,包括 cppcheck、cpplint、cppdepend、splint、tscancode、sonaqube 等,对比后认为 cppcheck 使用起来最方便,检查内容相对全面,支持多平台应用(linux 和 windows),且免费,因此选用 cppcheck 作为 c/c++ 代码静态检查的第一选择。本文对该工具的使用方法进行一个总结介绍。
2、特性介绍
cppceck 是一个 C/C++ 代码分析工具。与 C/C++ 编译器和许多其他分析工具不同,它不检测语法错误。cppcheck 仅检测编译器通常无法检测到的错误类型。目标是没有误报。
2.1、检查结果
- error:出现的错误
- warning:为了预防bug防御性编程建议信息越
- style:编码格式问题(没有使用的函数、多余的代码等)
- portablity:移植性警告。该部分如果移植到其他平台上,可能出现兼容性问题
- performance:建议优化该部分代码的性能
- information:一些有趣的信息,可以忽略
2.2、检查范围
- 自动变量检查;
- 数组的边界检查;
- class类检查;
- 过期的函数,废弃函数调用检查;
- 异常内存使用,释放检查;
- 内存泄漏检查,主要是通过内存引用指针;
- 操作系统资源释放检查,中断,文件描述符等;
- 异常STL 函数使用检查;
- 代码格式错误,以及性能因素检查。
2.3、支持的检查规则(列举一些):
- 禁止在头文件前有可执行代码。
- 引起二义性理解的逻辑表达式,必须使用括号显式说明优先级顺序。
- 逻辑判别表达式中的运算项必须要使用括号。
- 禁止对参数指针进行赋值。
- 动态分配的指针变量定义时如未被分配空间必须初始化为NULL
- 动态分配的指针变量第一次使用前必须进行是否为NULL的判别。
- 数组禁止越界使用。
- 数组下标必须是大于等于零的整型数。
- 禁止使用已被释放了的内存空间。
- 被free的指针必须指向最初malloc、calloc分配的地址。
- 建议用宏或const定义常数。
- 动态申请的内存空间用完后及时释放。
- 建议变量在声明的同时进行初始化。
- 函数中固定长度数组变量的传递必须使用引用方式。
- 定义为const的成员函数禁止返回非const的指针或引用。
- 禁止可导致非资源性对象数据被外部修改的成员函数返回。
- 捕获的顺序必须按由派生类到基类的次序排序。
- 每个指定的抛出必须有与之匹配的捕获。
- 异常抛出的对象必须使用引用方式捕获。
- 缺省捕获必须放在所有指定捕获之后。
- 禁止显式直接抛出
2.4、自定义规则
1. 使用 --suppress 选项过滤特定的警告:
如果你想要忽略某些警告,可以在命令行中使用 --suppress 选项。例如,如果你想要忽略所有的“缺少头文件”的警告,可以使用以下命令:
cppcheck --suppress=missingInclude ./# 这里,“missingInclude” 是要忽略的警告类型。将其替换为您希望过滤掉的警告类型。
2 . 编写自定义脚本:
在 CppCheck 运行结束后,使用自定义脚本对输出结果进行过滤。例如,您可以使用 Python 编写一个脚本,读取 CppCheck 的输出,然后根据自定义规则筛选警告信息。以下是一个简单的示例:import subprocess import sysdef main():cppcheck_command = "cppcheck --enable=all --xml --xml-version=2 ./"result = subprocess.run(cppcheck_command.split(), capture_output=True, text=True)# 在这里添加自定义规则def custom_filter(error):# 示例规则:过滤所有包含特定文件名的警告return "my_special_file.cpp" not in errorfiltered_errors = list(filter(custom_filter, result.stderr.splitlines()))for error in filtered_errors:print(error)if __name__ == "__main__":main()
这个示例脚本使用 subprocess.run 来运行 CppCheck,并捕获输出。然后,它根据自定义规则(在这里是忽略包含特定文件名的警告)对输出进行过滤。您可以在 custom_filter 函数中编写自己的过滤规则。
3.可以使用--rule和--rule-file选项添加此类规则。 也可以使用正则表达式,例如:
\sget[A-Za-z]+\(\)\s+{\s+return
这取决于代码库。
如果可以编写正则表达式,那么这是创建自定义规则的最直接,最简单的方法。
有关更多信息,请在此处阅读"写作规则"文章:cppcheck - Browse /Articles at SourceForge.net
但是也许想编写更复杂的规则,可以使用Cppcheck SymbolDatabase,tokenlist和语法树来搜索此类getter方法。 则不能使用--rule和--rule-file。 然后,有以下选择:
- 使用--dump并编写自己的自定义脚本,以读取输出数据(xml)。
- 编写C ++代码并将其编译为Cppcheck。
cppcheck 官方手册
https://cppcheck.sourceforge.io/manual.html
cppcheck 支持的检查内容列表如下
cppcheck / Wiki / ListOfChecks
3、linux 端
安装方法很简单,直接通过 apt 即可安装
sudo apt-ge install cppcheck
使用 help 指令查看使用方法,重要的部分标红处理
$ cppcheck --help
Cppcheck - A tool for static C/C++ code analysisSyntax:
cppcheck [OPTIONS] [files or paths]If a directory is given instead of a filename, *.cpp, *.cxx, *.cc, *.c++, *.c,
*.tpp, and *.txx files are checked recursively from the given directory.Options:
--cppcheck-build-dir=<dir>
Analysis output directory. Useful for various data.
Some possible usages are; whole program analysis,
incremental analysis, distributed analysis.
--check-config Check cppcheck configuration. The normal code
analysis is disabled by this flag.
--check-library Show information messages when library files have
incomplete info.
--config-exclude=<dir>
Path (prefix) to be excluded from configuration
checking. Preprocessor configurations defined in
headers (but not sources) matching the prefix will not
be considered for evaluation.
--config-excludes-file=<file>
A file that contains a list of config-excludes
--dump Dump xml data for each translation unit. The dump
files have the extension .dump and contain ast,
tokenlist, symboldatabase, valueflow.
-D<ID> Define preprocessor symbol. Unless --max-configs or
--force is used, Cppcheck will only check the given
configuration when -D is used.
Example: '-DDEBUG=1 -D__cplusplus'.
-U<ID> Undefine preprocessor symbol. Use -U to explicitly
hide certain #ifdef <ID> code paths from checking.
Example: '-UDEBUG'
-E Print preprocessor output on stdout and don't do any
further processing.
--enable=<id> Enable additional checks. The available ids are:
* all
Enable all checks. It is recommended to only
use --enable=all when the whole program is
scanned, because this enables unusedFunction.
* warning
Enable warning messages
* style
Enable all coding style checks. All messages
with the severities 'style', 'performance' and
'portability' are enabled.
* performance
Enable performance messages
* portability
Enable portability messages
* information
Enable information messages
* unusedFunction
Check for unused functions. It is recommend
to only enable this when the whole program is
scanned.
* missingInclude
Warn if there are missing includes. For
detailed information, use '--check-config'.
Several ids can be given if you separate them with
commas. See also --std
--error-exitcode=<n> If errors are found, integer [n] is returned instead of
the default '0'. '1' is returned
if arguments are not valid or if no input files are
provided. Note that your operating system can modify
this value, e.g. '256' can become '0'.
--errorlist Print a list of all the error messages in XML format.
--doc Print a list of all available checks.
--exitcode-suppressions=<file>
Used when certain messages should be displayed but
should not cause a non-zero exitcode.
--file-list=<file> Specify the files to check in a text file. Add one
filename per line. When file is '-,' the file list will
be read from standard input.
-f, --force Force checking of all configurations in files. If used
together with '--max-configs=', the last option is the
one that is effective.
-h, --help Print this help.
-I <dir> Give path to search for include files. Give several -I
parameters to give several paths. First given path is
searched for contained header files first. If paths are
relative to source files, this is not needed.
--includes-file=<file>
Specify directory paths to search for included header
files in a text file. Add one include path per line.
First given path is searched for contained header
files first. If paths are relative to source files,
this is not needed.
--include=<file>
Force inclusion of a file before the checked file. Can
be used for example when checking the Linux kernel,
where autoconf.h needs to be included for every file
compiled. Works the same way as the GCC -include
option.
-i <dir or file> Give a source file or source file directory to exclude
from the check. This applies only to source files so
header files included by source files are not matched.
Directory name is matched to all parts of the path.
--inconclusive Allow that Cppcheck reports even though the analysis is
inconclusive.
There are false positives with this option. Each result
must be carefully investigated before you know if it is
good or bad.
--inline-suppr Enable inline suppressions. Use them by placing one or
more comments, like: '// cppcheck-suppress warningId'
on the lines before the warning to suppress.
-j <jobs> Start <jobs> threads to do the checking simultaneously.
-l <load> Specifies that no new threads should be started if
there are other threads running and the load average is
at least <load>.
--language=<language>, -x <language>
Forces cppcheck to check all files as the given
language. Valid values are: c, c++
--library=<cfg> Load file <cfg> that contains information about types
and functions. With such information Cppcheck
understands your code better and therefore you
get better results. The std.cfg file that is
distributed with Cppcheck is loaded automatically.
For more information about library files, read the
manual.
--output-file=<file> Write results to file, rather than standard error.
--project=<file> Run Cppcheck on project. The <file> can be a Visual
Studio Solution (*.sln), Visual Studio Project
(*.vcxproj), or compile database
(compile_commands.json). The files to analyse,
include paths, defines, platform and undefines in
the specified file will be used.
--max-configs=<limit>
Maximum number of configurations to check in a file
before skipping it. Default is '12'. If used together
with '--force', the last option is the one that is
effective.
--platform=<type>, --platform=<file>
Specifies platform specific types and sizes. The
available builtin platforms are:
* unix32
32 bit unix variant
* unix64
64 bit unix variant
* win32A
32 bit Windows ASCII character encoding
* win32W
32 bit Windows UNICODE character encoding
* win64
64 bit Windows
* avr8
8 bit AVR microcontrollers
* native
Type sizes of host system are assumed, but no
further assumptions.
* unspecified
Unknown type sizes
--plist-output=<path>
Generate Clang-plist output files in folder.
-q, --quiet Do not show progress reports.
-rp, --relative-paths
-rp=<paths>, --relative-paths=<paths>
Use relative paths in output. When given, <paths> are
used as base. You can separate multiple paths by ';'.
Otherwise path where source files are searched is used.
We use string comparison to create relative paths, so
using e.g. ~ for home folder does not work. It is
currently only possible to apply the base paths to
files that are on a lower level in the directory tree.
--report-progress Report progress messages while checking a file.
--rule=<rule> Match regular expression.
--rule-file=<file> Use given rule file. For more information, see:
http://sourceforge.net/projects/cppcheck/files/Articles/
--std=<id> Set standard.
The available options are:
* posix
POSIX compatible code
* c89
C code is C89 compatible
* c99
C code is C99 compatible
* c11
C code is C11 compatible (default)
* c++03
C++ code is C++03 compatible
* c++11
C++ code is C++11 compatible
* c++14
C++ code is C++14 compatible (default)
More than one --std can be used:
'cppcheck --std=c99 --std=posix file.c'
--suppress=<spec> Suppress warnings that match <spec>. The format of
<spec> is:
[error id]:[filename]:[line]
The [filename] and [line] are optional. If [error id]
is a wildcard '*', all error ids match.
--suppressions-list=<file>
Suppress warnings listed in the file. Each suppression
is in the same format as <spec> above.
--template='<text>' Format the error messages. E.g.
'{file}:{line},{severity},{id},{message}' or
'{file}({line}):({severity}) {message}' or
'{callstack} {message}'
Pre-defined templates: gcc, vs, edit.
-v, --verbose Output more detailed error information.
--version Print out version number.
--xml Write results in xml format to error stream (stderr).
--xml-version=<version>
Select the XML file version. Currently only versions 2 is available.
使用示例
(1)检查当前路径下的代码,并输出到 txt 文件
cppcheck . --output-file=err.txt
(2)检查某个路径,不输出过程日志
cppcheck --quiet ../myproject/
(3)启用所有检查规则,检查某个文件
cppcheck --enable=all --inconclusive --std=posix test.cpp
(4)输出 xml 格式的日志文件
cppcheck src --enable=all --output-file=log.xml --xml
4、windows 端
在官网下载安装包,双击安装即可
打开 cppcheck 后新建一个扫描项目,导入代码路径
即可开始分析,分析完后可以在 查看--统计--统计 中查看总的扫描结果
同时可以实时查看每一个告警及错误的内容及对应的代码
在工具栏可以根据严重性进行过滤,比如之关注错误内容
相关文章:

CppCheck静态代码检查工具教程【Windows和Linux端】
目录 1、背景 2、特性介绍 2.1、检查结果 2.2、检查范围 2.3、支持的检查规则(列举一些): 2.4、自定义规则 3、linux 端 4、windows 端 1、背景 最近调研了几款 c/c 代码静态检查工具,包括 cppcheck、cpplint、cppdepend、splint、ts…...

W25Q128芯片手册精读
文章目录 前言1. 概述2. 特性3. 封装类型和引脚配置3.1 8焊盘WSON 8x6 mm3.2其他封装 4. 引脚描述4.1 片选4.2 串行数据输入输出4.3 写保护4.4 保持脚4.5 时钟 5. 块图6. 功能描述6.1 SPI功能6.1.1 标准SPI6.1.2 双通道SPI6.1.3 四通道SPI6.1.4 保持功能 6.2 写保护6.2.1 写保护…...

QT商业播放器
QT商业播放器 总体架构图 架构优点:解耦,采用生产者消费者设计模式,各个线程各司其职,通过消息队列高效协作 这个项目是一个基于ijkplayer和ffplayer.c的QT商业播放器, 项目有5部分构成: 前端QT用户界面 后端是集成了…...

Python的函数
近期遇到了一个没怎么看懂的Python函数的形式。 def twoSum(self, nums: List[int], target: int) -> List[int]: 后来上网查了资料。...

【物联网】STM32的中断机制不清楚?看这篇文章就足够了
在嵌入式系统中,中断是一种重要的机制,用于处理来自外部设备的异步事件。STM32系列微控制器提供了强大的中断控制器,可以方便地处理各种外部中断和内部中断。本文将详细介绍STM32中断的结构和使用方法。 文章目录 1. 什么叫中断2. 中断优先级…...

深入剖析红黑树:优雅地平衡二叉搜索树
目录 一.红黑树的概念二.插入操作三.与AVL树的比较 一.红黑树的概念 在之前的学习中,我们了解了二叉搜索平衡树,AVL树通过控制每个结点中的平衡因子的绝对值不超过1,实现了一个高性能的树。而相较于AVL的高度平衡,红黑树觉得AVL为…...

C10K问题:高并发模型设计
一、循环服务器模型 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/socket.h> //*******// #include &l…...

哈希/散列--哈希表[思想到结构][==修订版==]
文章目录 1.何为哈希?1.1百度搜索1.2自身理解1.3哈希方法/散列方法1.4哈希冲突/哈希碰撞1.5如何解决?哈希函数的设计 2.闭散列和开散列2.1闭散列/开放定址法2.2开散列/链地址法/开链法1.概念2.容量问题3.字符串问题4.开散列性能测试5.开散列与闭散列比较 3.代码实现[配备详细…...

成都建筑模板批发市场在哪?
成都作为中国西南地区的重要城市,建筑业蓬勃发展,建筑模板作为建筑施工的重要材料之一,在成都也有着广泛的需求。如果您正在寻找成都的建筑模板批发市场,广西贵港市能强优品木业有限公司是一家值得关注的供应商。广西贵港市能强优…...
亨元模式 结构型模式之六
1.定义 享元模式是一种结构型设计模式, 它允许你在消耗少量内存的情况下支持大量对象。 2.滑滑梯问题 在说明亨元模式之前,我们先看看关于滑滑梯的程序设计。小区的楼下只有三个滑滑梯,但是想玩的小朋友却非常多。怎么设计计滑滑梯资源的管理…...
面试题: Spring中Bean的实例化和Bean的初始化有什么区别?
Spring中Bean的实例化和Bean的初始化有什么区别? 背景答案扩展知识什么是实例化什么是初始化 个人评价我的回答 背景 想换工作, 看了图灵周瑜老师的视频想记录一下, 算是学习结果的一个输出. 答案 Spring 在创建一个Bean对象时, 会先创建出一个Java对象, 会通过反射来执行…...
阻塞队列,生产者消费者模型
目标: 1. 认识与使用阻塞队列 2. 认识与实现消费者模型 目录 阻塞队列的特点 生产者消费者模型 生产者消费者模型的优点 阻塞队列实现该模型 阻塞队列的特点 1. 线程安全 2. 带有阻塞特性 (1)如果队列为空,继续出队列&a…...

【RCRL充放电时间相关计算】
一. 基础知识 L、C元件称为“惯性元件”,即电感中的电流、电容器两端的电压,都有一定的“电惯性”,不能突然变化。充放电时间,不光与L、C的容量有关,还与充/放电电路中的电阻R有关。RC电路的时间常数:τRC…...
C++ primer plus--输入、输出和文件
17 输入、输出和文件 17.1 C 输入和输出概述 C 把输入和输出看做字节流。输入时,程序从输入流中抽取字节;输出时,程序将字节插到输出流中。 缓冲区是内存中的临时存储区域,是程序与文件或其他 I/O 设备之间的桥梁。 17.2 使用…...

案例题--Web应用考点
案例题--Web应用考点 负载均衡技术微服务XML和JSON无状态和有状态真题 在选择题中没有考察过web的相关知识,主要就是在案例分析题中考察 负载均衡技术 应用层负载均衡技术 传输层负载均衡技术 就近的找到距离最近的服务器,并进行分发 使用户就近获取…...
MySQL的SQL 优化:提升数据库性能
1. 插入操作优化 1.1 使用多值插入 通常情况下,插入大量数据时,使用多值插入语句比逐行插入更高效。例如,将多个数据行打包成一个 INSERT 语句: INSERT INTO users (name, email) VALUES (Alice, aliceexample.com), (Bob, bob…...

【匠心打造】从0打造uniapp 可视化拖拽设计 c_o 第十篇
一、click one for uniapp置顶: 全部免费开源 (你商业用途也没关系,不过可以告诉我公司名或者项目名,放在官网上好看点。哈哈-_-) 二、写在之前 距离上一篇更新已经大约4个月了,公司的事情,自己的一些琐事一直没时间…...

BIT-5-操作符详解(C语言初阶学习)
1. 各种操作符的介绍。 2. 表达式求值 1. 操作符分类: 算术操作符 移位操作符 位操作符 赋值操作符 单目操作符 关系操作符 逻辑操作符 条件操作符 逗号表达式 下标引用、函数调用和结构成员 2. 算术操作符 - * / % 除了 % 操作符…...

【重拾C语言】三、分支程序设计(双分支和单分支程序设计、逻辑判断、多分支程序设计、枚举类型表示;典型例题:判断闰年和求一元二次方程根)
目录 前言 三、分支程序设计 3.1 判断成绩是否及格——双分支程序设计 3.2 成绩加上获奖信息—单分支程序设计 3.3 逻辑判断——布尔类型 3.4 获奖分等级——多分支程序设计 3.5 表示汽车种类——枚举类型 3.6 例题 3.6.1 例题——判断某个年份是否闰年 3.6.2 例题—…...

Shiro应用到Web Application
一、权限基础 a) 认证(你是谁?) 判断你(被认证者)是谁的过程。通常被认证者提供用户名和密码。 常见的认证包含如下几种: 匿名认证:允许访问资源,不做任何类型的安全检查。表单认证:访问资源之前,需要提…...
线程与协程
1. 线程与协程 1.1. “函数调用级别”的切换、上下文切换 1. 函数调用级别的切换 “函数调用级别的切换”是指:像函数调用/返回一样轻量地完成任务切换。 举例说明: 当你在程序中写一个函数调用: funcA() 然后 funcA 执行完后返回&…...

【大模型RAG】Docker 一键部署 Milvus 完整攻略
本文概要 Milvus 2.5 Stand-alone 版可通过 Docker 在几分钟内完成安装;只需暴露 19530(gRPC)与 9091(HTTP/WebUI)两个端口,即可让本地电脑通过 PyMilvus 或浏览器访问远程 Linux 服务器上的 Milvus。下面…...

cf2117E
原题链接:https://codeforces.com/contest/2117/problem/E 题目背景: 给定两个数组a,b,可以执行多次以下操作:选择 i (1 < i < n - 1),并设置 或,也可以在执行上述操作前执行一次删除任意 和 。求…...

P3 QT项目----记事本(3.8)
3.8 记事本项目总结 项目源码 1.main.cpp #include "widget.h" #include <QApplication> int main(int argc, char *argv[]) {QApplication a(argc, argv);Widget w;w.show();return a.exec(); } 2.widget.cpp #include "widget.h" #include &q…...

HBuilderX安装(uni-app和小程序开发)
下载HBuilderX 访问官方网站:https://www.dcloud.io/hbuilderx.html 根据您的操作系统选择合适版本: Windows版(推荐下载标准版) Windows系统安装步骤 运行安装程序: 双击下载的.exe安装文件 如果出现安全提示&…...
uniapp中使用aixos 报错
问题: 在uniapp中使用aixos,运行后报如下错误: AxiosError: There is no suitable adapter to dispatch the request since : - adapter xhr is not supported by the environment - adapter http is not available in the build 解决方案&…...

LINUX 69 FTP 客服管理系统 man 5 /etc/vsftpd/vsftpd.conf
FTP 客服管理系统 实现kefu123登录,不允许匿名访问,kefu只能访问/data/kefu目录,不能查看其他目录 创建账号密码 useradd kefu echo 123|passwd -stdin kefu [rootcode caozx26420]# echo 123|passwd --stdin kefu 更改用户 kefu 的密码…...

推荐 github 项目:GeminiImageApp(图片生成方向,可以做一定的素材)
推荐 github 项目:GeminiImageApp(图片生成方向,可以做一定的素材) 这个项目能干嘛? 使用 gemini 2.0 的 api 和 google 其他的 api 来做衍生处理 简化和优化了文生图和图生图的行为(我的最主要) 并且有一些目标检测和切割(我用不到) 视频和 imagefx 因为没 a…...

使用LangGraph和LangSmith构建多智能体人工智能系统
现在,通过组合几个较小的子智能体来创建一个强大的人工智能智能体正成为一种趋势。但这也带来了一些挑战,比如减少幻觉、管理对话流程、在测试期间留意智能体的工作方式、允许人工介入以及评估其性能。你需要进行大量的反复试验。 在这篇博客〔原作者&a…...

(一)单例模式
一、前言 单例模式属于六大创建型模式,即在软件设计过程中,主要关注创建对象的结果,并不关心创建对象的过程及细节。创建型设计模式将类对象的实例化过程进行抽象化接口设计,从而隐藏了类对象的实例是如何被创建的,封装了软件系统使用的具体对象类型。 六大创建型模式包括…...