5

I would like to use CMake and clang-tidy in my project, however I see that build times are quite a bit higher when I use this in all the main cmake file:

set(CMAKE_CXX_CLANG_TIDY
  clang-tidy-11;
  -format-style='file';
  -header-filter=${CMAKE_CURRENT_SOURCE_DIR};
)

It is working well, but I don't want to have this build-time penalty every time I build the project during development. Therefore I thought I would make a separate target that builds all, but uses clang-tidy. And when I do a regular debug or release build it does not do any checking. However I don't know how to do this in Cmake. Do I make a custom target with a command "cmake --build" with a target_set_property of CMAKE_CXX_CLANG_TIDY?

This feels rather clunky, so my question is, are there other ways to do this?

Frank
  • 2,446
  • 7
  • 33
  • 67

1 Answers1

8

however I see that build times are quite a bit higher when I use this in all the main cmake file:

You're going to have to pay for the cost of running clang-tidy sometime or another. It's essentially running the first few phases of a compiler to analyze your code and look for errors.

Setting CMAKE_CXX_CLANG_TIDY runs clang-tidy in line with your build, as you have observed.

This feels rather clunky, so my question is, are there other ways to do this?

Yes. When using the Ninja or Makefile generators, you may set -DCMAKE_EXPORT_COMPILE_COMMANDS=ON at the command line. That will create a file called compile_commands.json in your build folder that the standalone clang-tidy can read.

In sum, at the command line, you would manually run:

$ cmake -G Ninja -S . -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
$ clang-tidy-11 -format-style=file -header-filter=. -p build

The -p flag tells clang-tidy in which directory to find your compile_commands.json.

Alex Reinking
  • 16,724
  • 5
  • 52
  • 86
  • 1
    Note that simply copying the commands from this answer won't work, clang-tidy still needs a list of source files to target, simply supplying the `-p` path to `compile_commands.json` is not sufficient, see e.g. https://stackoverflow.com/questions/75330301/using-clang-tidy-with-compile-commands-json-to-parse-multiple-files – CNugteren Aug 25 '23 at 14:31