Tutorial on how to use the cppcheck static code inspection tool

Mondo Technology Updated on 2024-02-04

Recently, I have investigated several C C++ static check tools, including CPPcheck, CPPLINT, CPPdepend, SPLINT, TSCancode, Sonaqube, etc., and after comparison, I believe that CPPcheck is the most convenient to use, the inspection content is relatively comprehensive, supports multi-platform applications (Linux and Windows), and is free, so I chose CPPcheck as the first choice for C C++ static check. This article provides a summary of how to use this tool.

CPPCECK is a C C++ analysis tool. Unlike the C++ compiler and many other parsing tools, it does not detect syntax errors. cppcheck only detects error types that compilers normally can't detect. The goal is to have no false positives .

Test results include:

error: An error occurred.

warning: In order to prevent bugs, defensive programming is recommended to provide more information.

style: Encoding format issues (unused functions, redundant **, etc.).

portablity: portability warning. If this part is ported to other platforms, there may be compatibility issues.

performance: It is recommended to optimize the performance of this section.

information: Some interesting information that can be ignored.

The scope of the inspection is:

Automatic variable checking;

bounds checking of arrays;

class inspection;

Expired functions, obsolete function call checks;

Abnormal memory usage, release check;

Memory leak checking, mainly through memory reference pointers;

Operating system resource release checks, interrupts, file descriptors, etc.;

Abnormal STL function usage checks;

* Format errors, as well as performance factor checks.

CPPcheck Official Manual.

The following table describes the checks that cppcheck supports.

cppcheck / wiki / listofchecks

The installation method is simple, and it can be installed directly through the apt.

sudo apt-ge install cppcheck

Use the help command to see how to use it, and the important parts are marked in red.

cppcheck –help

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,.tpp, and *.txx files are checked recursively from the given directory.

options:

cppcheck-build-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 h**e

incomplete info.

config-exclude=

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=

a file that contains a list of config-excludes

dump dump xml data for each translation unit. the dump

files h**e the extension .dump and contain ast,tokenlist, symboldatabase, valueflow.

d 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 undefine preprocessor symbol. use -u to explicitly

hide certain #ifdef code paths from checking.

example: ‘udebug’

e print preprocessor output on stdout and don’t do any

further processing.

enable= enable additional checks. the **ailable ids are:

allenable all checks. it is recommended to only

use –enable=all when the whole program is

scanned, because this enables unusedfunction.

warning

enable warning messages

styleenable 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= 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 **ailable checks.

exitcode-suppressions=

used when certain messages should be displayed but

should not cause a non-zero exitcode.

file-list= 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.

igive 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=

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=

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.

igive 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 start threads to do the checking simultaneously.

l specifies that no new threads should be started if

there are other threads running and the load **erage is

at least .

language=, -x

forces cppcheck to check all files as the given

language. valid values are: c, c++

library= load file 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= write results to file, rather than standard error.

project= run cppcheck on project. the 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=

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=, –platform=

specifies platform specific types and sizes. the

*ailable 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

win6464 bit windows

*r88 bit **r microcontrollers

native

type sizes of host system are assumed, but no

further assumptions.

unspecified

unknown type sizes

plist-output=

generate clang-plist output files in folder.

q, –quiet do not show progress reports.

rp, –relative-paths

rp=, –relative-paths=

use relative paths in output. when given, 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= match regular expression.

rule-file= use given rule file. for more information, see:

std= set standard.

the **ailable options are:

posixposix compatible code

c89c code is c89 compatible

c99c code is c99 compatible

c11c code is c11 compatible (default)

c++03c++ code is c++03 compatible

c++11c++ code is c++11 compatible

c++14c++ code is c++14 compatible (default)

more than one –std can be used:

cppcheck –std=c99 –std=posix file.c’

suppress= suppress warnings that match . the format of

is:[error id]:[filename]:[line]

the [filename] and [line] are optional. if [error id]

is a wildcard ‘*all error ids match.

suppressions-list=

suppress warnings listed in the file. each suppression

is in the same format as above.

template=‘’ format the error messages. e.g.,or‘()or

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=

select the xml file version. currently only versions 2 is **ailable.

Example of use. 1) Check the ** in the current path and output to the txt file.

cppcheck . output-file=err.txt

2) Check a certain path, do not output process logs.

cppcheck --quiet ../myproject/

3) Enable all check rules to check a certain file.

cppcheck --enable=all --inconclusive --std=posix test.cpp

4) Output log files in XML format.

cppcheck src --enable=all --output-file=log.xml --xml

On the official website**Install the package, double-click to install.

After opening cppcheck, create a new scan project and import the path.

After the analysis, you can view the total scan results in View Statistics.

At the same time, you can view the content of each alarm and error in real time and the corresponding **.

In the toolbar, you can filter by severity, such as focusing on erroneous content.

Related Pages