About ClangFormat

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:

  1. Open a terminal
  2. Type nano .bashrc and hit enter.
  3. Paste the following near the bottom of the file:
    1. alias format='find . -name "*.cpp" -o -name "*.c" -o -name "*.h"|xargs -I {} clang-format -i {}'
  4. Close the file with Shift+X and then enter Y when prompted if you would like to save the file.
  5. Type source .bashrc
  6. If there are no errors, then go back into the directory you'd like to run clang-format in, type format, and hit enter.
  7. 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.

This guide was first published on Jan 18, 2018. It was last updated on Jan 18, 2018.

This page (Formatting with clang-format) was last updated on Apr 15, 2021.

Text editor powered by tinymce.