How to use clang-tidy for C++

A practical and efficient linter!

How to use clang-tidy for C++

In one of the articles here on the blog we published about clang-format, today we are going to know another Clang/LLVM application collection tool: clang-tidy.

Clang-Tidy is a linter for C++. Its purpose is to provide an extensible framework for diagnosing and correcting typical programming errors such as style violations, interface misuse, or bugs that can be deduced through static analysis.

To install clang-tidy just use the same procedures described in the clang-format article.


The simplest way to check your code with clang-tidy is: suppose you have the code below that prints a pointer instead of the reference or the data itself:


#include <iostream>

int main(){
   const char* str {};
   std::cout << *str << '\n';

Even if you compile with the proper parameters of your compiler to detect failures, you will not be able to detect the warning.

Using the command below with clang-tidy you can detect:

clang-tidy main.cpp -- -Imy_project/include -DMY_DEFINES ...

The output will appear:

1 warning generated.
main.cpp:5:16: warning: Dereference of null pointer (loaded from variable 'str') [clang-analyzer-core.NullDereference]
   std::cout << *str << '\n';
main.cpp:4:3: note: 'str' initialized to a null pointer value
   const char* str {};
main.cpp:5:16: note: Dereference of null pointer (loaded from variable 'str')
   std::cout << *str << '\n';

clang-tidy has its own checks and can also run Clang Static Analyzer checks. Each check has a name and the checks to be performed can be chosen using the -checks= option, which specifies a list separated by commas and -, for example:

clang-tidy main.cpp -checks=-*,clang-analyzer-*,-clang-analyzer-cplusplus*

This command will disable all default checks (-*) and enable all clang-analyzer-* except clang-analyzer-cplusplus*.

In summary, it is a useful tool and used by default in most configurations for LSP.

For more information use clang-tidy --help and read the official documentation.

Some alternatives to clang-tidy:

cpp cppdaily clang