Clang-Tidy is a command line tool designed to automatically analyze and improve C and C++ source code. It performs static code analysis to catch common bugs, style violations, performance issues, and more. Integrating Clang-Tidy into the development workflow helps maintain code quality, enforce best practices, and prevent subtle errors early. By running Clang-Tidy inside a Docker container with all dependencies preinstalled, you can ensure consistent analysis across all team members without requiring local setup - everyone uses the same version, minimizing discrepancies and simplifying maintenance.
Here's an example of a simple C source file, main.c
:
#include <stdio.h>
int main() {
char a[3] = {10, 20, 30};
printf("%d\n", a[3]);
return 0;
}
To analyze the code using Clang-Tidy from a Docker container, run the following command:
docker run -it --rm -v ./:/src xianpengshen/clang-tools:20 clang-tidy main.c -- -std=c99
docker run
- starts a new Docker container.-it
- runs the container in interactive mode with a terminal attached.--rm
- removes the container automatically after it exits, keeping the system clean.-v ./:/src
- mounts the current directory into the container at/src
, allowing access to the project files.xianpengshen/clang-tools
- specifies the Docker image to use.clang-tidy main.c
- runs the static analysis tool for given source file.--
- separates Clang-Tidy options from the compiler options that follow.-std=c99
- indicates that the code should be interpreted according to the C99 standard, which helps Clang-Tidy accurately understand and analyze the source.
Note: Clang-Tidy knows how to locate standard headers like stddef.h
, so there's no need to provide them using the -I
option when running inside the container. However, you can specify multiple -I
options to add additional directories, ensuring all necessary headers are accessible 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 issues a warning that accessing a[3]
is out of bounds and the value is not initialized.
Leave a Comment
Cancel reply