Skip to content

clang-tidy does not find issues for some checks in source files added with #include "some_file.cpp" #165695

@codelimit

Description

@codelimit

Consider the following example:

lib.hpp:

#pragma once

#include <string>

namespace tidy
{
    class base
    {
    public:
        virtual ~base() = default;
        base();
        base(const base& other) = default;
        base(base&& other) = default;
        base& operator=(const base& other) = default;
        base& operator=(base&& other) = default;

    protected:
        void on_construct();
        virtual void foo() = 0;

    private:
        std::string* str = nullptr;
    };
}

lib.cpp:

#include "lib.hpp"

#include <iostream>

namespace tidy
{
    base::base()
    {
        on_construct();
    }

    void base::on_construct()
    {
        // the following check is introduced intentionally, to show that
        // clang-tidy actually examines file, finds one issue and skips other
        if (str = nullptr)
        {
            std::cout << "null\n";
        }
        foo();
    }
}

test.cpp:

#include "lib.cpp"

If I run clang-tidy lib.cpp --header-filter=.*, it finds two issues:

  1. an assignment within an 'if' condition
  2. Call to pure virtual method 'base::foo' during construction has undefined behavior

However if I run clang-tidy test.cpp --header-filter=.*, it finds only one:

  1. an assignment within an 'if' condition

⚠️ This issue skips a lot of potential errors in a project if using cmake unity build. As most of you know, unity build increases compile time and also increase clang-tidy scan time. Having a large project (over 5k files), clang-tidy found 40 more issues when I switched off unity build.

Any hints are highly appreciated.


It does not depend on presence of compilation database (I intentionally skipped it), but for those who care, I add simple cmake file:
CMakeLists.txt:

cmake_minimum_required(VERSION 4.0)
project(tidy)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_CXX_SCAN_FOR_MODULES OFF)

#add_library(tidy STATIC lib.cpp)
add_library(tidy STATIC test.cpp)
target_include_directories(tidy PUBLIC ${CMAKE_CURRENT_LIST_DIR})

To generate database, use
cmake -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ -S . -B build
and then append -p build to clang-tidy cmd:
clang-tidy test.cpp --header-filter=.* -p build

I also attach the archive with sample project tidy.zip

clang-tidy version: LLVM version 21.1.4

Best regards.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions