ClangFormat is a command line tool that automatically formats C, C++, Java, JavaScript, Objective-C, and other source code according to a set of style rules. It helps maintain consistent coding style across a codebase and reduces manual formatting. This tutorial shows how to install ClangFormat on Ubuntu 24.04.
Install ClangFormat
Use the following command to download the ClangFormat binary from the GitHub repository's releases page:
sudo wget -qO /usr/local/bin/clang-format https://github.com/cpp-linter/clang-tools-static-binaries/releases/latest/download/clang-format-20_linux-amd64
Set execute permission for a file:
sudo chmod a+x /usr/local/bin/clang-format
We can check ClangFormat version as follows:
clang-format --version
Testing ClangFormat
Let's say we have the C code snippet saved in the main.c
file:
#include <stdio.h>
int main() {
for(int i=0;i<10;++i){printf("%d\n",i);}
return 0;
}
Run ClangFormat on this file using the following command:
clang-format -i main.c
After running the command, the code is automatically reformatted to follow the default style rules:
#include <stdio.h>
int main() {
for (int i = 0; i < 10; ++i) {
printf("%d\n", i);
}
return 0;
}
As you can see, ClangFormat improves readability by applying consistent indentation and spacing.
Uninstall ClangFormat
To uninstall ClangFormat, simply delete the associated file:
sudo rm -rf /usr/local/bin/clang-format
Leave a Comment
Cancel reply