ClangFormat is a command line tool that automatically formats source code - such as C, C++, Java, JavaScript, Objective-C, and more - based on predefined style guidelines. Having a standardized format improves readability and ensures consistency across the project. By using a Docker container that already has ClangFormat preinstalled, you can run formatting commands in a clean, isolated environment - no system-wide installations needed. It ensures everyone on the team runs the same version of ClangFormat, eliminating inconsistencies caused by tool version differences.
Suppose we have a simple C source file, main.c
, that looks like this:
#include <stdio.h>
int main() {
for(int i=0;i<10;++i){printf("%d\n",i);}
return 0;
}
To format the code using ClangFormat from a Docker container, run the following command:
docker run -it --rm -v ./:/src -u $(id -u):$(id -g) xianpengshen/clang-tools:20 clang-format -i main.c
Explanation of the command:
docker run
- launches a new Docker container.-it
- enables interactive mode with a terminal session.--rm
- automatically removes the container after it finishes running to keep the system tidy.-v ./:/src
- mounts the current working directory into the container at/src
.-u $(id -u):$(id -g)
- ensures the container runs with the local user permissions.xianpengshen/clang-tools
- specifies the Docker image to use.clang-format -i main.c
- runs the formatter onmain.c
and updates the file in place.
After the command runs, the main.c
file will be reformatted in place to follow the default style:
#include <stdio.h>
int main() {
for (int i = 0; i < 10; ++i) {
printf("%d\n", i);
}
return 0;
}
Leave a Comment
Cancel reply