Cppcheck
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
Cppcheck
Version
1.79.99

Overview

Cppcheck is a simple tool for static analysis of C/C++ code.

When you write a checker you have access to:

Use –debug on the command line to see debug output for the token list and the syntax tree. If both –debug and –verbose is used, the symbol database is also written.

The checks are written in C++. The checks are addons that can be easily added/removed.

Writing a check

Below is a simple example of a check that detect division with zero:

{
// Iterate through all tokens in the token list
for (const Token *tok = _tokenizer->tokens(); tok; tok = tok->next())
{
// is this a division or modulo?
if (Token::Match(tok, "[/%]")) {
// try to get value '0' of rhs
const ValueFlow::Value *value = tok->astOperand2()->getValue(0);
// if 'value' is not NULL, rhs can be zero.
if (value)
reportError(tok, Severity::error, "zerodiv", "Division by zero");
}
}
}

The function Token::Match is often used in the checks. Through it you can match tokens against patterns. It is currently not possible to write match expressions that uses the syntax tree, the symbol database, nor the library. Only the token list is used.

Creating a new check class from scratch

Check classes inherit from the Check class. The Check class specifies the interface that you must use. To integrate a check class into cppcheck all you need to do is:

Embedding Cppcheck

Cppcheck is designed to be easily embeddable into other programs.

The "cli/main.cpp" and "cli/cppcheckexecutor.*" files illustrate how cppcheck can be embedded into an application.

Detailed overview

This happens when you execute cppcheck from the command line:

  1. CppCheckExecutor::check this function executes the Cppcheck
  2. CppCheck::parseFromArgs parse command line arguments
    • The Settings class is used to maintain settings
    • Use FileLister and command line arguments to get files to check
  3. ThreadExecutor create more instances of CppCheck if needed
  4. CppCheck::check is called for each file. It checks a single file
  5. Preprocess the file (through Preprocessor)
    • Comments are removed
    • Macros are expanded
  6. Tokenize the file (see Tokenizer)
  7. Run the runChecks of all check classes.
  8. Simplify the tokenlist (Tokenizer::simplifyTokenList2)
  9. Run the runSimplifiedChecks of all check classes

When errors are found, they are reported back to the CppCheckExecutor through the ErrorLogger interface