Static analysis of C/C++ code

Cppcheck

GitHub Actions Linux Build Status Windows Build Status OSS-Fuzz Coverity Scan Build Status License
Github Action Status Linux Build Status Windows Build Status OSS-Fuzz Coverity Scan Build Status License

About the name

The original name of this program was "C++check", but it was later changed to "Cppcheck".

Despite the name, Cppcheck is designed for both C and C++.

Manual

A manual is available online.

Donate CPU

Cppcheck is a hobby project with limited resources. You can help us by donating CPU (1 core or as many as you like). It is simple:

  1. Download (and extract) Cppcheck source code.
  2. Run script: python cppcheck/tools/donate-cpu.py.

The script will analyse debian source code and upload the results to a cppcheck server. We need these results both to improve Cppcheck and to detect regressions.

You can stop the script whenever you like with Ctrl C.

Compiling

Any C++11 compiler should work. For compilers with partial C++11 support it may work. If your compiler has the C++11 features that are available in Visual Studio 2013 / GCC 4.6 then it will work.

To build the GUI, you need Qt.

When building the command line tool, PCRE is optional. It is used if you build with rules.

There are multiple compilation choices:

  • qmake - cross platform build tool
  • cmake - cross platform build tool
  • Windows: Visual Studio (VS 2013 and above)
  • Windows: Qt Creator + mingw
  • gnu make
  • g++ 4.6 (or later)
  • clang++

cmake

Example, compiling Cppcheck with cmake:

mkdir build
cd build
cmake ..
cmake --build .

If you want to compile the GUI you can use the flag. -DBUILD_GUI=ON

For rules support (requires pcre) use the flag. -DHAVE_RULES=ON

For release builds it is recommended that you use: -DUSE_MATCHCOMPILER=ON

Using cmake you can generate project files for Visual Studio,XCode,etc.

qmake

You can use the gui/gui.pro file to build the GUI.

cd gui
qmake
make

Visual Studio

Use the cppcheck.sln file. The file is configured for Visual Studio 2019, but the platform toolset can be changed easily to older or newer versions. The solution contains platform targets for both x86 and x64.

To compile with rules, select "Release-PCRE" or "Debug-PCRE" configuration. pcre.lib (pcre64.lib for x64 builds) and pcre.h are expected to be in /externals then. A current version of PCRE for Visual Studio can be obtained using vcpkg.

Visual Studio (from command line)

If you do not wish to use the Visual Studio IDE, you can compile cppcheck from the command line the following command.

msbuild cppcheck.sln

VS Code (on Windows)

Install MSYS2 to get GNU toolchain with g++ and gdb (https://www.msys2.org/). Create a settings.json file in the .vscode folder with the following content (adjust path as necessary):

{
    "terminal.integrated.shell.windows": "C:\\msys64\\usr\\bin\\bash.exe",
    "terminal.integrated.shellArgs.windows": [
        "--login",
    ],
    "terminal.integrated.env.windows": {
        "CHERE_INVOKING": "1",
        "MSYSTEM": "MINGW64",
    }
}

Run "make" in the terminal to build cppcheck.

For debugging create a launch.json file in the .vscode folder with the following content, which covers configuration for debugging cppcheck and misra.py:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "cppcheck",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/cppcheck.exe",
            "args": [
                "--dump",
                "${workspaceFolder}/addons/test/misra/misra-test.c"
            ],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": true,
            "MIMode": "gdb",
            "miDebuggerPath": "C:/msys64/mingw64/bin/gdb.exe",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        },
        {
            "name": "misra.py",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/addons/misra.py",
            "console": "integratedTerminal",
            "args": [
                "${workspaceFolder}/addons/test/misra/misra-test.c.dump"
            ]
        }
    ]
}

Qt Creator + MinGW

The PCRE dll is needed to build the CLI. It can be downloaded here: http://software-download.name/pcre-library-windows/

GNU make

Simple, unoptimized build (no dependencies):

make

The recommended release build is:

make MATCHCOMPILER=yes FILESDIR=/usr/share/cppcheck HAVE_RULES=yes CXXFLAGS="-O2 -DNDEBUG -Wall -Wno-sign-compare -Wno-unused-function"

Flags:

  1. MATCHCOMPILER=yes Python is used to optimise cppcheck. The Token::Match patterns are converted into C++ code at compile time.

  2. FILESDIR=/usr/share/cppcheck Specify folder where cppcheck files are installed (addons, cfg, platform)

  3. HAVE_RULES=yes Enable rules (PCRE is required if this is used)

  4. CXXFLAGS="-O2 -DNDEBUG -Wall -Wno-sign-compare -Wno-unused-function" Enables most compiler optimizations, disables cppcheck-internal debugging code and enables basic compiler warnings.

g++ (for experts)

If you just want to build Cppcheck without dependencies then you can use this command:

g++ -o cppcheck -std=c++11 -Iexternals -Iexternals/simplecpp -Iexternals/tinyxml2 -Iexternals/picojson -Ilib cli/*.cpp lib/*.cpp externals/simplecpp/simplecpp.cpp externals/tinyxml2/*.cpp

If you want to use --rule and --rule-file then dependencies are needed:

g++ -o cppcheck -std=c++11 -lpcre -DHAVE_RULES -Ilib -Iexternals -Iexternals/simplecpp -Iexternals/tinyxml2 cli/*.cpp lib/*.cpp externals/simplecpp/simplecpp.cpp externals/tinyxml2/*.cpp

MinGW

mingw32-make LDFLAGS=-lshlwapi

Other Compiler/IDE

  1. Create an empty project file / makefile.
  2. Add all cpp files in the cppcheck cli and lib folders to the project file / makefile.
  3. Add all cpp files in the externals folders to the project file / makefile.
  4. Compile.

Cross compiling Win32 (CLI) version of Cppcheck in Linux

sudo apt-get install mingw32
make CXX=i586-mingw32msvc-g++ LDFLAGS="-lshlwapi" RDYNAMIC=""
mv cppcheck cppcheck.exe

Packages

You can install Cppcheck with yum/apt/brew/etc.

The official rpms are built with these files: https://src.fedoraproject.org/rpms/cppcheck/tree/master

Webpage

https://cppcheck.sourceforge.io/

Owner
Daniel Marjamäki
Lives in Sweden with wife and son. Works full time as C++ developer at Edgeware (TV streaming). Works on open source software in spare time.
Daniel Marjamäki
Comments
  • Addition of a document type definition for library configurations

    Addition of a document type definition for library configurations

    A document type definition can help to work with corresponding files because it describes the involved data structures to some degree. Such a DTD can be added so that further improvements will become easier for the safe data exchange around library configurations for static source code analysis.

    A DTD format was standardised as a basis for XML documents. Some technical challenges and limitations were noticed so that another standard like W3C XML Schema evolved. Such a XML schema definition can also be added so that corresponding file handling might become more consistent.

    • Would you like to try this approach out?
    • How are the chances to integrate this update suggestion into your source code repository?
  • Add a dynamic rule enable/disable system

    Add a dynamic rule enable/disable system

    First, each rule now has a "state" attribute:

    enabled => rule is enabled ... disabled => rule is disabled. ...

    Second, each rule has a list of IDs of rules to disable and a list of rules to enable if fired:

    ... thatrule thisrule disabled thisrule ... thatrule ...

    Initially, the first and third rule are enabled. When the first rule gets fired, then the third rule becomes disabled and the second rule becomes enabled.

    Note that the behavior of this system is undefined when the rule to be enabled or disabled should fire on the same source fragment which fired the controlling rule.

  • Check that virtual function non-narrow access modifier in derived class

    Check that virtual function non-narrow access modifier in derived class

    That's kind a weird style when derived class has a private method which is public in parent. You can't invoke it directly but could cast it to parent and invoke.

  • Initial QT support

    Initial QT support

    Hi guys,

    We've been using cppcheck for our QT project but we kept getting false-positives from some of the functions that were exposed to QT so I've done a small patch that'll scan the code for Q_PROPERTY variables and also tokenize the QML (essentially javascript) sudo-code for calls that reference the C/C++ code.

    //commit ---------------------------------------------------------------------------------------------

    • Will check for Q_PROPERTY fields and remove them from the unused function list
    • Will parse the .qml files (if they're in the source list of files to check) and remove references to C/C++ functions which would have otherwise been unused.

    Use --enable=all or --enable=qt etc to enable the functionality and add the *.qml (i.e. src/assets) path to the command line interface invocation.

  • Bug #2524: Addition of CMake build files

    Bug #2524: Addition of CMake build files

    This is my third proposal for the building of the Cppcheck software with the tool "CMake" in this year. I hope that the chances will increase for integration of the suggested adjustments into your source repository.

    Would you like to accept this retry?

  • donate-cpu-server.py: added stale report / cleanups

    donate-cpu-server.py: added stale report / cleanups

    I recognized several entries in the crash report which were outdated and when trying to run them locally it turned out the archive was no longer available. There's probably even more cases which might lead to the results not being updated, but there's currently no way to find this packages so I added a stale report which will show the results which are older than 30 days.

    I also added the date and time to the crash report so it is easier to see which of the results are recent.

  • Add cpack packaging capability

    Add cpack packaging capability

    Linux distributions frequently lag behind actual releases. This offers users the opportunity to create their own packages easily.

    Example usage:

    $ mkdir build && cd build
    $ cmake -DCPACK_GENERATOR=RPM ..
    $ make package
    

    Note that the version info is automatically computed from the output of git describe --tags.

  • Project configuration with CMake

    Project configuration with CMake

    Hi!

    I would like to help to the project with this small contribution. I added a new way to configure, compile and install the project using CMake. I think that for people familiar with this tool, the configuration, build and installation of the project is more intuitive. I didn't touch none of the previous configurations, and all of them can live together.

    Right now, I only tested that on Ubuntu 14.04 but It should be generic for any Linux distribution. If you decide to accept the contribution I can also deal with the Windows building (probably some minor changes should be made for that purpose).

    I have also some other ideas easy to implement with CMake that could be interesting for the project.

  • Fix issue 8413: Condition is always false 'i=expr; if (i != expr) {}'

    Fix issue 8413: Condition is always false 'i=expr; if (i != expr) {}'

    When comparing same expression, this will follow variables if the variable hasn't been modified:

    void f() { const int i = sizeof(int);  if ( i != sizeof (int)){}}
    
  • Extend command line to support --xml-results=<file> option

    Extend command line to support --xml-results= option

    For integration with cmake and jenkins for a large-scale codebase, we'd like the XML results to be written to a specific file, rather than going to standard error.

  • Check for functions calls in sizeof calculations

    Check for functions calls in sizeof calculations

    A common mistake that I have found in our codebase is calling a function to get an integer or enum that represents the type such as:

    int numBytes = numElements * sizeof(x.GetType());
    

    This extends cppcheck for sizeof calculation to check for function calls as well.

  • LCppC backport: Support member variables in CheckOther::checkIncompleteArrayFill()

    LCppC backport: Support member variables in CheckOther::checkIncompleteArrayFill()

    This has a known test failure, but I actually do not know, why. In LCppC, this works, because Z::b.a gets a varid. In cppcheck it does not (anymore). Do you know, why, and if this is wanted how to workaround it?

  • Fix handling of std::optional, operator* might be non const

    Fix handling of std::optional, operator* might be non const

    Fix handling of std::optional, operator* might be non const

    Also, there was an issue in detecting string iterators, the detection was relying on the container being templates, using the '>' as part of the pattern, which is not the case with std::string for instance.

    Without any change, TestSymbolDatabase::iterator would fail, while TestSymbolDatabase::iterator2 (which is the same thing but with auto instead of std::string::const_iterator) would succeed.

    The changes in Library::detectContainer are a bit of a hack, I'm not very proud of them...

  • Selfcheck callgrind

    Selfcheck callgrind

    Using the unusedFunction self-check for profiling gives us a very basic case which involves the core functionality without the valueflow or most of the checks which should be a pretty good canary for speed improvements/regressions. Although the Ir does not translate directly into actual real time speed it would affects other jobs like the sanitized builds and would give an indication if it has any impact at all.

Pharos Static Binary Analysis Framework

Automated static analysis tools for binary programs

Jun 22, 2022
ELF static analysis and injection framework that parse, manipulate and camouflage ELF files.

elfspirit elfspirit is a useful program that parse, manipulate and camouflage ELF files. It provides a variety of functions, including adding or delet

Jun 15, 2022
A static analysis tool that helps security researchers scan a list of Windows kernel drivers for common vulnerability patterns in drivers (CVE makers!)
A static analysis tool that helps security researchers scan a list of Windows kernel drivers for common vulnerability patterns in drivers (CVE makers!)

Driver Analyzer A static analysis tool that helps security researchers scan a list of Windows kernel drivers for common vulnerability patterns in driv

Jun 13, 2022
Static code checker for C++

cpplint - static code checker for C++ Cpplint is a command-line tool to check C/C++ files for style issues following Google's C++ style guide. Cpplint

Jun 21, 2022
Qt-oriented static code analyzer based on the Clang framework

WARNING: master is the development branch. Please use the v1.10 branch. clazy v1.11 clazy is a compiler plugin which allows clang to understand Qt sem

Jun 22, 2022
A static analyzer for Java, C, C++, and Objective-C
A static analyzer for Java, C, C++, and Objective-C

Infer Infer is a static analysis tool for Java, C++, Objective-C, and C. Infer is written in OCaml. Installation Read our Getting Started page for det

Jun 17, 2022
Static analyzer for C/C++ based on the theory of Abstract Interpretation.

IKOS IKOS (Inference Kernel for Open Static Analyzers) is a static analyzer for C/C++ based on the theory of Abstract Interpretation. Introduction IKO

Jun 17, 2022
Static analyzer for C/C++ based on the theory of Abstract Interpretation.

IKOS IKOS (Inference Kernel for Open Static Analyzers) is a static analyzer for C/C++ based on the theory of Abstract Interpretation. Introduction IKO

Jun 13, 2022
Analysis of Argon and Xenon Collision data to test Bardeen-Cooper-Schrieffer Approximation

Univeristy of North Carolina Wilmington Analysis of Argon and Xenon Collision data to test Bardeen-Cooper-Schrieffer Approximation. Argon Data Tree Fi

Nov 15, 2021
Clang build analysis tool using -ftime-trace

Clang Build Analyzer Clang C/C++ build analysis tool when using Clang 9+ -ftime-trace. The -ftime-trace compiler flag (see blog post or Clang 9 releas

Jun 16, 2022
将 C/C++ 代码转换成流程图 / Turn your C/C++ code into flowchart
将 C/C++ 代码转换成流程图 / Turn your C/C++ code into flowchart

将 C/C++ 代码转换成流程图 / Turn your C/C++ code into flowchart

Jun 17, 2022
CITL's static analysis engine for native code artifacts

citl-static-analyzer Fast binary hardening analysis tooling. Building on Linux The build process varies by Linux distribution, owing to differences be

Feb 14, 2022
Static analysis of C/C++ code

Cppcheck GitHub Actions Linux Build Status Windows Build Status OSS-Fuzz Coverity Scan Build Status License About the name The original name of this p

Jun 22, 2022
Pharos Static Binary Analysis Framework

Automated static analysis tools for binary programs

Jun 22, 2022
ELF static analysis and injection framework that parse, manipulate and camouflage ELF files.

elfspirit elfspirit is a useful program that parse, manipulate and camouflage ELF files. It provides a variety of functions, including adding or delet

Jun 15, 2022
A static analysis tool that helps security researchers scan a list of Windows kernel drivers for common vulnerability patterns in drivers (CVE makers!)
A static analysis tool that helps security researchers scan a list of Windows kernel drivers for common vulnerability patterns in drivers (CVE makers!)

Driver Analyzer A static analysis tool that helps security researchers scan a list of Windows kernel drivers for common vulnerability patterns in driv

Jun 13, 2022
Cmake check - Static analysis for CMake files.
Cmake check - Static analysis for CMake files.

cmake_check Cmake_check is a linter for the CMake language. It takes a set of user-defined rules and reports violations for CMakeLists.txt files and C

Mar 22, 2020
Static analysis of structures is a fundamental step for determining the stability of structures

StAnD: A Dataset of Linear Static Analysis Problems [Abstract] [Paper] Static analysis of structures is a fundamental step for determining the stabili

Jan 20, 2022
Terrain Analysis Using Digital Elevation Models (TauDEM) software for hydrologic terrain analysis and channel network extraction.

TauDEM (Terrain Analysis Using Digital Elevation Models) is a suite of Digital Elevation Model (DEM) tools for the extraction and analysis of hydrolog

Jun 13, 2022