Skip to content
Tutorials Center
My learning

Topics

Lesson 120 of 171 ยท Errors and Debugging

clang-tidy and Static Analysis

Catch C++ bugs before running the program. Turn on compiler warnings, configure clang-tidy checks, read its diagnostics, fix typical findings and run analysis in CI.

Some bugs do not need a test to find them. A comparison between a signed and an unsigned number, a function whose result is silently ignored, a virtual function that was meant to override and doesn't: the compiler or a separate tool can often see these just by reading your code. This is static analysis: examining source code without running it.

In this lesson you will use three layers. First, compiler warnings, the cheapest and fastest layer. Second, clang-tidy, a linter with hundreds of named checks, many of which can also fix the code for you. Third, deeper analyzers and how to run all of it in a build. Static analysis complements assert and debugging tools, which find problems while the program runs, and it helps you avoid the traps described in Undefined Behavior.

flowchart LR
    A["Source code"] --> B["Compiler warnings<br/>(-Wall -Wextra)"]
    B --> C["clang-tidy<br/>(named checks)"]
    C --> D["Deeper analyzers<br/>(Clang Static Analyzer, cppcheck)"]
    D --> E["Run-time tools<br/>(sanitizers, tests)"]

Static checks go from fastest and noisiest on the left to slower and more precise; run-time tools catch what is left.

Layer 1: compiler warnings

Your compiler is already a static analyzer, but it stays quiet unless you ask. Start every project with these flags (GCC and Clang):

Terminal
g++ -std=c++23 -Wall -Wextra -Wpedantic -Wshadow -Wconversion -Wsign-conversion main.cpp
Flag Catches
-Wall A large, useful bundle: unused variables, missing returns, suspicious comparisons
-Wextra More: unused parameters, missing field initializers
-Wpedantic Code that is not standard C++
-Wshadow A local variable hiding another one with the same name
-Wconversion Implicit conversions that may lose data (double to int, long to int)
-Wsign-conversion Implicit conversions between signed and unsigned

Two more habits help. Treat warnings as errors in CI with -Werror, so new warnings cannot slip in. Do not use -Werror for builds that other people run with newer compilers, since a new compiler may add warnings that break your old code. On Windows with MSVC, the equivalent is /W4 (and /WX for warnings as errors). Compiler options are covered in Compiler Flags and Optimization.

A bug that warnings find

The classic example is comparing signed and unsigned numbers. In C++, the signed value is converted to unsigned first, and -1 becomes a huge number:

C++ The signed/unsigned trap and its fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The plain comparison prints false, even though -1 is obviously less than 3. A warning at compile time costs you nothing; the same bug in production can mean a failed bounds check. The fix, std::cmp_less from <utility>, belongs to the same family as the checked conversions you saw in Type Conversions.

Layer 2: clang-tidy

clang-tidy is a command-line tool from the LLVM project. It parses your code with the real Clang front end and runs checks. Each check has a name made of a group and a topic, such as bugprone-use-after-move or modernize-use-nullptr. Groups you will meet most often:

Group Purpose Example check
bugprone-* Likely bugs bugprone-use-after-move, bugprone-integer-division
modernize-* Replace old style with modern C++ modernize-use-nullptr, modernize-use-override
performance-* Avoidable work performance-unnecessary-value-param, performance-for-range-copy
readability-* Clearer code readability-container-size-empty
cppcoreguidelines-* The C++ Core Guidelines cppcoreguidelines-owning-memory
clang-analyzer-* Path-sensitive analysis (see below) clang-analyzer-core.NullDereference
misc-*, concurrency-*, cert-* Assorted, thread safety, secure coding misc-const-correctness

Running it

clang-tidy needs to know how each file is compiled (include paths, defines, standard). CMake can write that into a file called compile_commands.json:

Terminal
cmake -S . -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
clang-tidy -p build src/main.cpp

You can also let CMake run clang-tidy during every build:

CMAKE
set(CMAKE_CXX_CLANG_TIDY clang-tidy)

Without a compilation database, pass the flags after --: clang-tidy main.cpp -- -std=c++23.

Reading a diagnostic

Suppose a file contains this class:

C++
class Shape {
public:
    virtual ~Shape() = default;
    virtual double area() const = 0;
};

class Square : public Shape {
public:
    Square(double side) : side_(side) {}
    double area() const { return side_ * side_; }
private:
    double side_;
};

clang-tidy reports each finding with a file, line, message and check name in square brackets:

TEXT
shapes.cpp:9:5: warning: single-argument constructors must be marked explicit
    to avoid unintentional implicit conversions [google-explicit-constructor]
shapes.cpp:10:12: warning: annotate this function with 'override' or (rarely) 'final'
    [modernize-use-override]

The name in brackets is how you search for documentation, turn the check off, or silence one line. The fixed class:

C++ Applying what the analyzer asked for

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

explicit stops Square s = 3.0; from silently converting a number into a shape. override makes the compiler check that a base-class virtual function really exists, which catches a mismatched const or a typo. [[nodiscard]] warns when a caller ignores a result that should be used. All three are explained further in Virtual Functions and Constructors.

Choosing checks with .clang-tidy

Put a file named .clang-tidy at the project root. Everything below is read-only configuration:

YAML
Checks: >
  -*,
  bugprone-*,
  modernize-*,
  performance-*,
  readability-container-size-empty,
  -modernize-use-trailing-return-type
WarningsAsErrors: 'bugprone-*'
HeaderFilterRegex: '^.*/src/.*'
FormatStyle: file

Read the Checks list from left to right: -* turns everything off, the following lines turn groups on, and a leading - turns a single check off again. WarningsAsErrors promotes selected checks to failures. HeaderFilterRegex decides which headers are reported, so you do not drown in warnings from third-party libraries.

Start small. A project with 10,000 warnings gets ignored. Enable bugprone-*, fix what it finds, then add a group at a time.

Fixing automatically

Many checks come with a fix-it. Apply them with --fix, then review the diff:

Terminal
clang-tidy -p build --checks='modernize-use-nullptr,modernize-use-override' --fix src/*.cpp
git diff

Never commit fixes you have not looked at, and commit them separately from other changes so the history stays readable.

Silencing a false positive

Static analysis guesses, so occasionally it is wrong. Suppress the single line and explain why:

C++
// The buffer is owned by the C library that called us.
char* raw = static_cast<char*>(handle);  // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast)

NOLINTNEXTLINE(check-name) suppresses the next line, and NOLINTBEGIN / NOLINTEND wrap a block. Always name the check; a bare NOLINT hides everything, including future real bugs.

Layer 3: path-sensitive analysis

Some bugs only happen on certain paths through a function. The Clang Static Analyzer (the clang-analyzer-* checks, also available as scan-build) follows possible execution paths symbolically. It can report that a pointer may be null on the path where if (x) is false, or that memory leaks on an early return:

C++
int* find(int* data, int n, int wanted) {
    for (int i = 0; i < n; ++i) {
        if (data[i] == wanted) {
            return &data[i];
        }
    }
    return nullptr;
}

int firstMatch(int* data, int n) {
    int* hit = find(data, n, 42);
    return *hit;   // analyzer: dereference of null pointer on the path where nothing was found
}

This is slower than the cheap checks, so many teams run it nightly or in CI rather than on every save. cppcheck is another popular free analyzer with its own rules and low false-positive rate; PVS-Studio and SonarQube are commercial options. Compilers have their own deep analyzers too: GCC's -fanalyzer and MSVC's /analyze.

Putting it in your workflow

flowchart TD
    A["Edit code"] --> B["Editor runs clang-tidy<br/>(clangd shows warnings live)"]
    B --> C["Commit"]
    C --> D["CI: build with -Wall -Wextra -Werror"]
    D --> E["CI: clang-tidy on changed files"]
    E --> F["CI: tests + sanitizers"]

A layered pipeline: fast feedback while editing, strict gates in continuous integration.

  • Editor: the clangd language server runs clang-tidy while you type and shows squiggles with the check name.
  • Pre-commit: run clang-tidy on the files you changed, not the whole project.
  • CI: compile with warnings as errors, run clang-tidy, and follow with tests under sanitizers.
  • Legacy code: keep a baseline. Fail the build only on warnings in new lines so you can improve gradually.

Static analysis finds a class of bugs, not all of them. It never replaces tests, and a clean run does not prove the program is correct. Treat each finding as a question: is this really a bug? If yes, fix it. If it is a false positive, suppress it with a comment explaining why.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the clang-tidy diagnostic "[modernize-use-override]", what does the text in square brackets tell you?

    Every diagnostic ends with the check's name. Use it in .clang-tidy to enable or disable the check and in NOLINT comments to suppress a single line.
  2. 2. What does clang-tidy need to analyze a file the same way your compiler would?

    Include paths, defines and the language standard change how code parses. CMake can export compile_commands.json, or you can pass flags after --.
  3. 3. Which check configuration enables only bugprone checks?

    Checks are applied left to right. The leading -* switches everything off, then bugprone-* turns that group on.
  4. 4. Why is a bare // NOLINT comment a poor way to silence a warning?

    Name the check, as in NOLINT(check-name), and say why. Then only the known false positive is hidden.

Summary

  • Static analysis examines code without running it. Use layers: compiler warnings, clang-tidy, deeper analyzers, then run-time tools and tests.
  • Enable -Wall -Wextra -Wpedantic -Wshadow -Wconversion, and use -Werror in your own CI.
  • clang-tidy checks are named group-topic; choose them in .clang-tidy, give it a compile_commands.json, and apply fix-its with --fix only after reviewing them.
  • explicit, override, final and [[nodiscard]] turn many bugs into compile-time diagnostics.
  • Suppress false positives with NOLINT(check-name) and a reason; never with a bare NOLINT.
  • Path-sensitive analyzers (Clang Static Analyzer, cppcheck, -fanalyzer) find null dereferences and leaks across branches, but run slower, so use them in CI.

Next: I/O Streams in Depth, the library behind cin, cout and file I/O.