CMake with clang-tidy

CMake can use clang-tidy as a build option for a CMake project by adding a few parameters to CMakeLists.txt. It’s also possible to use clang-tidy without modifying CMakeLists.txt. Generate the file compile_commands.json used by clang-tidy. You don’t have to build the project as we are interested in checking and possibly fixing the C++ source code.

To install clang-tidy:

  • macOS: brew install llvm, then edit ~/.zshrc, adding the line alias clang-tidy=$(brew --prefix llvm)/bin/clang-tidy or similar
  • Linux: apt install clang-tidy or similar
cmake -Bbuild -DCMAKE_EXPORT_COMPILE_COMMANDS=on

Run clang-tidy. Specify options or use a file .clang-tidy, which is usually in the top directory of the project.

clang-tidy -p build/ <glob or files>

To fix the errors, add clang-tidy option --fix.