Clang-Tidy is a command line tool that performs static analysis on C and C++ source code to identify bugs, stylistic issues, and performance improvements. It helps enforce coding standards, catch potential errors early, and maintain high-quality, readable code across a project. This tutorial explains how to install Clang-Tidy on Ubuntu 24.04.
Prepare environment
Clang-Tidy requires access to standard headers such as stddef.h
, which are provided by the compiler itself - either GCC or Clang. To ensure proper analysis, make sure you have a compiler like GCC or Clang installed, as they include these internal headers needed for parsing.
sudo apt install -y gcc
Install Clang-Tidy
Download the Clang-Tidy binary from the GitHub repository's releases page using the following command:
sudo wget -qO /usr/local/bin/clang-tidy https://github.com/cpp-linter/clang-tools-static-binaries/releases/latest/download/clang-tidy-20_linux-amd64
Set execute permission for a file:
sudo chmod a+x /usr/local/bin/clang-tidy
You can check the Clang-Tidy version with the following command:
clang-tidy --version
Testing Clang-Tidy
Suppose the following C code snippet is saved in a file named main.c
:
#include <stdio.h>
int main() {
char a[3] = {10, 20, 30};
printf("%d\n", a[3]);
return 0;
}
Execute Clang-Tidy on this file with the following command:
clang-tidy main.c -- -std=c99 -I/usr/lib/gcc/x86_64-linux-gnu/13/include
--
- separates Clang-Tidy options from compiler options.-std=c99
- specifies that the code should be parsed using the C99 standard. This is important so Clang-Tidy understands the code properly.-I/usr/lib/gcc/x86_64-linux-gnu/13/include
- adds a directory where GCC internal headers (likestddef.h
) are located. We can specify multiple-I
options to include additional directories as needed, ensuring all required headers are found during analysis.
Output:
2 warnings generated.
/home/adminer/main.c:5:5: warning: 2nd function call argument is an uninitialized value [clang-analyzer-core.CallAndMessage]
5 | printf("%d\n", a[3]);
| ^ ~~~~
/home/adminer/main.c:5:5: note: 2nd function call argument is an uninitialized value
5 | printf("%d\n", a[3]);
| ^ ~~~~
/home/adminer/main.c:5:20: warning: array index 3 is past the end of the array (that has type 'char[3]') [clang-diagnostic-array-bounds]
5 | printf("%d\n", a[3]);
| ^ ~
/home/adminer/main.c:4:5: note: array 'a' declared here
4 | char a[3] = {10, 20, 30};
| ^
Clang-Tidy warns that accessing a[3]
is out-of-bounds and not initialized.
Uninstall Clang-Tidy
To uninstall Clang-Tidy, just remove the related file:
sudo rm -rf /usr/local/bin/clang-tidy
Leave a Comment
Cancel reply