Using clang-tidy with CMake 3.6

In CMake 3.6 a new property was introduced to support clang-tidy. clang-tidy can perform static analysis of your code and provide you with additional information to compiler warnings. In this post we'll take a look at how to make use of the new CMake property to add clang-tidy to our projects. If you're interested in how to use the different features of clang-tidy, I refer you to Google :).

Finding clang-tidy

clang-tidy may not be available on all systems, so in typical cmake fashion we first attempt to find the executable. If the executable is available, I setup a convenient CMake list (DO_CLANG_TIDY) that will help when using the CMake property later. In this case, I have enabled all checks with *, and then subsequently disabled checks that are currently in alpha (using the * wildcard). After you run clang-tidy with your application, you will likely disable additional checks. In that case, you will need to separate removed checks with a comma and ensure they are prefixed with a -.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
find_program(
  CLANG_TIDY_EXE
  NAMES "clang-tidy"
  DOC "Path to clang-tidy executable"
  )
if(NOT CLANG_TIDY_EXE)
  message(STATUS "clang-tidy not found.")
else()
  message(STATUS "clang-tidy found: ${CLANG_TIDY_EXE}")
  set(DO_CLANG_TIDY "${CLANG_TIDY_EXE}" "-checks=*,-clang-analyzer-alpha.*")
endif()

Setting the property

With DO_CLANG_TIDY, we can now set the CXX_CLANG_TIDY (assuming you are using C++) property for all targets we want to analyze.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
set_target_properties(
  my-target-name PROPERTIES
  CXX_STANDARD 14
  CXX_STANDARD_REQUIRED ON
  COMPILE_FLAGS "${WARNING_FLAGS}"
)

if(CLANG_TIDY_EXE)
  set_target_properties(
    my-target-name PROPERTIES
    CXX_CLANG_TIDY "${DO_CLANG_TIDY}"
  )
endif()

The above will enable C++14 and setup some custom warning flags. If clang-tidy is available, then it will run DO_CLANG_TIDY whenever we build the target. That's basically all there is to it!