ClangFormat (often called Clang) is a tool that allows you to automatically format C, C++, and Objective-C files. It makes your code more readable and saves your time and the time of anyone reviewing your code for a pull request by making it so neither of you has to worry about formatting very much. On Adafruit repositories, clang-format is run automatically on every commit and pull request, but you still have to run it locally since when it is run through a CI, it just tells you what needs to be reformatted without actually reformatting it.
Step 1) Install clang-format
For mac/linux, you can install with a package manager
macOS:
brew install clang-format
If you don't already have Homebrew installed, you can do it here
Linux:
sudo apt install clang-format
Windows:
Download the "Windows Installer" from the "Windows Snapshot Builds" section from the link below.
Step 2) Run it
Navigate to the folder you'd like to run clang-format in and then run the following command, replacing File_To_Format.cpp with the filename of the file you'd like to format:
clang-format -i File_To_Format.cpp
Step 3) Add an alias to your .bashrc (optional)
I've found it can be really useful to have one simpler command that runs clang on all the pertinent files in a directory, and I modified a command from our Arduino CI repository to do that. Here's how you can use that too.
Linux:
- Open a terminal
- Type
nano .bashrc
and hit enter. - Paste the following near the bottom of the file:
alias format='find . -name "*.cpp" -o -name "*.c" -o -name "*.h"|xargs -I {} clang-format -i {}'
- Close the file with Shift+X and then enter Y when prompted if you would like to save the file.
- Type
source .bashrc
- If there are no errors, then go back into the directory you'd like to run clang-format in, type
format
, and hit enter. - The command should look through the directory you're in and run clang-format on all .cpp, .c, and .h files.
These instructions may work on mac, but you will have to replace .bashrc
with .bash_profile
.
Text editor powered by tinymce.