cppcheck使用

2023-11-09

cppcheck说明

cppcheck主要用来检查c/c++代码的,本文主要讲述cppcheck用命令行方式在linux平台的使用, window平台提供界面操作请自行安装使用。

cppcheck能够检查出来的问题

检查结果包括
error:出现的错误
warning:为了预防bug防御性编程建议信息越
style:编码格式问题(没有使用的函数、多余的代码等)
portablity:移植性警告。该部分如果移植到其他平台上,可能出现兼容性问题
performance:建议优化该部分代码的性能
information:一些有趣的信息,可以忽略

检查范围是
自动变量检查;
数组的边界检查;
class类检查;
过期的函数,废弃函数调用检查;
异常内存使用,释放检查;
内存泄漏检查,主要是通过内存引用指针;
操作系统资源释放检查,中断,文件描述符等;
异常STL 函数使用检查;
代码格式错误,以及性能因素检查。

cppcheck使用并生成html结果


Cppcheck - A tool for static C/C++ code analysis

Syntax:
    cppcheck [OPTIONS] [files or paths]

If a directory is given instead of a filename, *.cpp, *.cxx, *.cc, *.c++, *.c, *.ipp,
*.ixx, *.tpp, and *.txx files are checked recursively from the given directory.

Options:
    --addon=<addon>
                         Execute addon. i.e. --addon=cert. If options must be
                         provided a json configuration is needed.
    --addon-python=<python interpreter>
                         You can specify the python interpreter either in the
                         addon json files or through this command line option.
                         If not present, Cppcheck will try "python3" first and
                         then "python".
    --bug-hunting
                         Enable noisy and soundy analysis. The normal Cppcheck
                         analysis is turned off.
    --cppcheck-build-dir=<dir>
                         Cppcheck work folder. Advantages:
                          * whole program analysis
                          * faster analysis; Cppcheck will reuse the results if
                            the hash for a file is unchanged.
                          * some useful debug information, i.e. commands used to
                            execute clang/clang-tidy/addons.
    --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.
    --clang=<path>       Experimental: Use Clang parser instead of the builtin Cppcheck
                         parser. Takes the executable as optional parameter and
                         defaults to `clang`. Cppcheck will run the given Clang
                         executable, import the Clang AST and convert it into
                         Cppcheck data. After that the normal Cppcheck analysis is
                         used. You must have the executable in PATH if no path is
                         given.
    --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'.
    -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', 'warning',
                                  'performance' and 'portability' are enabled.
                          * performance
                                  Enable performance messages
                          * portability
                                  Enable portability messages
                          * information
                                  Enable information messages
                          * unusedFunction
                                  Check for unused functions. It is recommended
                                  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.
    --exitcode-suppressions=<file>
                         Used when certain messages should be displayed but
                         should not cause a non-zero exitcode.
    --file-filter=<str>  Analyze only those files matching the given filter str
                         Can be used multiple times
                         Example: --file-filter=*bar.cpp analyzes only files
                                  that end with bar.cpp.
    --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.
    -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.
    --max-ctu-depth=N    Max depth in whole program analysis. The default value
                         is 2. A larger value will mean more errors can be found
                         but also means the analysis will be slower.
    --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), compile database (compile_commands.json),
                         or Borland C++ Builder 6 (*.bpr). The files to analyse,
                         include paths, defines, platform and undefines in
                         the specified file will be used.
    --project-configuration=<config>
                         If used together with a Visual Studio Solution (*.sln)
                         or Visual Studio Project (*.vcxproj) you can limit
                         the configuration cppcheck should check.
                         For example: '--project-configuration=Release|Win32'
    --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
                          * elbrus-e1cp
                                 Elbrus e1c+ architecture
                          * pic8
                                 8 bit PIC microcontrollers
                                 Baseline and mid-range architectures
                          * pic8-enhanced
                                 8 bit PIC microcontrollers
                                 Enhanced mid-range and high end (PIC18) architectures
                          * pic16
                                 16 bit PIC microcontrollers
                          * mips32
                                 32 bit MIPS 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=<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:
                          * 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
                          * c++17
                                 C++ code is C++17 compatible
                          * c++20
                                 C++ code is C++20 compatible (default)
    --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.
    --suppress-xml=<file>
                         Suppress warnings listed in a xml file. XML file should
                         follow the manual.pdf format specified in section.
                         `6.4 XML suppressions` .
    --template='<text>'  Format the error messages. Available fields:
                           {file}              file name
                           {line}              line number
                           {column}            column number
                           {callstack}         show a callstack. Example:
                                                 [file.c:1] -> [file.c:100]
                           {inconclusive:text} if warning is inconclusive, text
                                               is written
                           {severity}          severity
                           {message}           warning message
                           {id}                warning id
                           {cwe}               CWE id (Common Weakness Enumeration)
                           {code}              show the real code
                           \t                 insert tab
                           \n                 insert newline
                           \r                 insert carriage return
                         Example formats:
                         '{file}:{line},{severity},{id},{message}' or
                         '{file}({line}):({severity}) {message}' or
                         '{callstack} {message}'
                         Pre-defined templates: gcc (default), cppcheck1 (old default), vs, edit.
    --template-location='<text>'
                         Format error message location. If this is not provided
                         then no extra location info is shown.
                         Available fields:
                           {file}      file name
                           {line}      line number
                           {column}    column number
                           {info}      location info
                           {code}      show the real code
                           \t         insert tab
                           \n         insert newline
                           \r         insert carriage return
                         Example format (gcc-like):
                         '{file}:{line}:{column}: note: {info}\n{code}'
    -U<ID>               Undefine preprocessor symbol. Use -U to explicitly
                         hide certain #ifdef <ID> code paths from checking.
                         Example: '-UDEBUG'
    -v, --verbose        Output more detailed error information.
    --version            Print out version number.
    --xml                Write results in xml format to error stream (stderr).

Example usage:
  # Recursively check the current folder. Print the progress on the screen and
  # write errors to a file:
  cppcheck . 2> err.txt

  # Recursively check ../myproject/ and don't print progress:
  cppcheck --quiet ../myproject/

  # Check test.cpp, enable all checks:
  cppcheck --enable=all --inconclusive --library=posix test.cpp

  # Check f.cpp and search include files from inc1/ and inc2/:
  cppcheck -I inc1/ -I inc2/ f.cpp

For more information:
    https://cppcheck.sourceforge.io/manual.pdf

Many thanks to the 3rd party libraries we use:
 * tinyxml2 -- loading project/library/ctu files.
 * picojson -- loading compile database.
 * pcre -- rules.
 * qt -- used in GUI
 * z3 -- theorem prover from Microsoft Research used in bug hunting.


在平时的代码检查中可以参考如下命令:
cppcheck j2 --enable=style code/* --xml 2> err.xml
代码都在code下面
j 参数指定的是检查线程的个数,
-i 后面加路径 一般用来忽略代码中带的第三方库

生成html结果

cppcheck-htmlreport --file=err.xml --report-dir=ret --source-dir=.
输出的结果在ret下面,打开index.html就可以查看

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

cppcheck使用 的相关文章

随机推荐

  • 高德地图自定义车辆定位marker以及弹出框窗口

    地图安装 npm install vue amap save 项目中设置高德地图 安装成功后在main js设置以下内容 import VueAMap from vue amap Vue use VueAMap VueAMap initAM
  • 邻接矩阵无向图

    邻接矩阵 无向图和有向图在邻接矩阵中的表示方法 无向图和有向图大同小异 在这里只以无向图为例 代码部分通过简单调整即可对应编译有向图 邻接矩阵数据类型定义 define MaxVertices 100 定义最大容量 typedef stru
  • ASP.NET系统用户权限设计与实现

    引言 电子商务系统对安全问题有较高的要求 传统的访问控制方法DAC Discretionary Access Control 自主访问控制模型 MAC Mandatory Access Control 强制访问控制模型 难以满足复杂的企业环
  • react-native及npm install 安装问题

    我们项目中已经开始用react native 所以swift学习放下一段时间 学了一个月的rn 今天分享记录学习过程 学习资料整理 1 react native 中文网 http reactnative cn docs 0 27 getti
  • Qt-认清信号槽的本质

    目录 放个目录方便预览 这个目录是从博客复制过来的 点击会跳转到博客 简介 猫和老鼠的故事 对象之间的通信机制 尝试一 直接调用 尝试二 回调函数 映射表 观察者模式 Qt的信号 槽 信号 槽简介 信号 槽分两种 信号 槽的实现 元对象编译
  • 数据研发面经——字节跳动

    数据研发面经 字节跳动 1 抽象类与接口 2 多态 3 四种引用 4 锁 并发怎么处理 5 进程和线程的区别 6 shuffle机制 mapreduce流程 7 JVM虚拟机 为什么需要虚拟机 8 内存区域 五部分 栈和堆区别 具体存放的东
  • 2017.10.9 DZY Loves Math VI 失败总结

    一看到love math就知道肯定不会做 首先lcm拆成i j gcd i j 然后就讨论分子和分母 但并没有什么卵用 这个题对比传统反演题 主要不同的是f函数不是很直观 所以如果枚举gcd 那剩下的两个数一定互质 然后就按照gcd 1的反
  • 思科VoIP配置清单(转)

    我配过简单的VoIP 用的是思科的设备 希望对你有用 R1接口为192 168 1 1 R2接口为192 168 1 2 R1 R2直连 并相互各连两部电话 要想实现互相通话 可以做如下配置 其中 5164765 6239560为连接R1的
  • C# 创建Excel并写入内容

    在许多应用程序中 需要将数据导出为Excel表格 以便用户可以轻松地查看和分析数据 在本文中 我们将讨论如何使用C 创建Excel表格 并将数据写入该表格 添加引用 在C 中创建Excel表格 需要使用Microsoft Office In
  • Typora和PicGo-Core搭配使用(解决博客单独上传图片问题)

    前言 本文简单介绍快速上传图片并获取图片 URL 链接的工具 图片存放到Gitee仓库中 在博客网站发布时不必担心图片转存失败问题 解决本地图片在网站需单独上传的难题 将本地图片存储在网络中 图床 并生成URL 联网情况下通过URL链接即可
  • Unity之六:项目实战篇

    文章目录 一 一个简单的实例 二 使用CMake组织项目与Unity 2 1 目录结构 2 2 CMakeLists txt的编写 2 3 使用实例 一 一个简单的实例 一个测试单元是源文件 测试文件和Unity构成的 把他们放在一起进行编
  • 【算法提升】——异或理解,位的运算

    个人主页 努力学习的少年 版权 本文由 努力学习的少年 原创 在CSDN首发 需要转载请联系博主 如果文章对你有帮助 欢迎关注 点赞 收藏 一键三连 和订阅专栏哦 目录 一 只出现一次的数字 1 二 数组中只出现一次的数字2 一 只出现一次
  • localStorage在Safari浏览器无痕模式下失效

    Safari无痕模式是不能使用localStorage的 可以利用这个特性判断用户是否开启无痕模式 并提醒用户关闭无痕模式 if typeof localStorage object try localStorage setItem loc
  • 学习笔记 JavaScript ES6 异步编程Promise

    Promise ES里面对异步操作的第一种方案 学习Promise 让异常操作变得优雅 Promise的精髓在于异步操作的状态管理 一个Promise最基本用法 他的参数是一个方法 这个方法里有两个参数 一个是异步操作执行成功的回调 一个是
  • DC综合脚本中文详细解释

    script for Design Compiler DC综合编译脚本 language TCL 语言说明 Usage 使用说明 1 make sure the lib in the current directory 确保设计库在正确的文
  • Xcode项目设置项中的LLVM

    LLVM是构架编译器
  • html5开发手机打电话发短信功能,html5的高级开发,html5开发大全,html手机电话短信功能详解

    原文地址 http blog csdn net xmtblog article details 32931905 在很多的手机网站上 有打电话和发短信的功能 对于这些功能是如何实现的呢 其实不难 今天我们就用html5来实现他们 简单的让你
  • Angular--官方文档之 Angular CLI

    学习Angular官方文档的时候 参考https angular cn guide quickstart 这个快速开发的文档 对于我这个AngularJs小白在看了Angular菜鸟教程后 只能说可以简单的运用一下 看到一些专业术语 我也是
  • 嵌入式Linux(四)—嵌入式C语言(杂项/数据类型关键字)

    目录 杂项关键字 sizeof Return 数据类型关键字 char 进制 int long short Unsigned signed Float double void 自定义数据类型 Struct Union enum typede
  • cppcheck使用

    cppcheck使用 cppcheck说明 cppcheck能够检查出来的问题 cppcheck使用并生成html结果 生成html结果 cppcheck说明 cppcheck主要用来检查c c 代码的 本文主要讲述cppcheck用命令行