Home

clang-format notes

clang-format is an auto code formatter. I use it for C/C++ projects.

Different linux PCs, different clang-format versions

Some options for fomatting specified in .clang-format file don’t work for versions 10 and below. Most of the linux PCs use Ubuntu which packages this software based on Ubuntu OS version. And even the latest Ubuntu OS version might not include the latest clang-format software version. Thus the options in the format file will be unrecognized when running on a system which has older clang-format software.

Solution: docker

I came across a well maintained, frequently updated, permissive Apache 2.0 licensed docker image xianpengshen/clang-tools which has all the latest versions of clang-format (versions 17, 18, etc.).

Format 1 file -

docker run --volume $PWD:/src --user $UID xianpengshen/clang-tools:18 clang-format -i list.c

Notes -

Format all files (.c, .cpp and .h) recursively from current directory -

find . -name "*.cpp" -o -name "*.c" -o -name "*.h" | xargs -I {} docker run --volume $PWD:/src --user $UID xianpengshen/clang-tools:17 clang-format -i {}

Local vs on github? (via CI)

The above method is local-only usage. You can do it, but you will often forget it. Therefore, we need a bot to do it. However, it should not do it for all the commits because otherwise it will be hectic to git pull everytime after git push on one branch. So, I would like to run it only on PRs.

github ‘Actions’ workflow bots

Sample PR on my public github repo -

https://github.com/devprabal/small-linklist/pull/9

In this PR, see the github workflow file, the .clang-format file and .clang-format-ignore file.

Pitfalls

// clang-format off
my_struct array[] = { {.member1 = something1, .member2 = something2, }, {.member1 = otherthing1, .member2 = otherthing2, },  };
// clang-format on

Unexplored areas