Analyze with build environment

clang-tidy is easier to work with if a compile command database is set for the project. Compilation database is needed to figure out specific build options for each file. Clang-tidy can use a compilation database (compile_commands.json file) which is generated by CMake.

In the next steps this document assumes that CMake and Python 3 programs are installed.

First create a simple folder structure with only one source file. Let the parent folder name be example/.

  1. Put the following main.cpp file into example/.

    #include <iostream>
    
    int main()
    {
        std::cout << "Hello World!";
        return 0;
    }
  2. Put the following CMakeLists.txt file into example/ folder and replace <clang_installation_path> with the actual installed LLVM toolchain path.

# Create project "example"
project(example)
# With this option CMake will generate the compile_commands.json
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# Set the C and C++ compilers paths
set(CMAKE_C_COMPILER "<clang_installation_path>/bin/clang")
set(CMAKE_CXX_COMPILER "<clang_installation_path>/bin/clang++")
# Add main.cpp file of the project root directory as a source file
set(SOURCE_FILES main.cpp)
# Add executable target with source files listed in SOURCE_FILES variable
add_executable(example ${SOURCE_FILES})
  1. generate the Makefiles and the compile_commands.json into build/ folder.

    cmake -S . -B build/
  2. Run the run-clang-tidy python script which is located in the same directory as the clang-tidy. This script is a wrapper of the clang-tidy tool and also takes the compile_commands.json as an input. The script lists all the applied checks and shows the warnings. In this example all checks are enabled.

    python3 ~/community/clang/v19.1.6/bin/run-clang-tidy -p build/ -checks=*
  3. Navigate to build/ folder and run the make command to compile the project.

    make

Based on the above clang-tidy can also analyze a project with build environment.