So now to get it, we need to compile LLVM! I wish brew provides something like
--with-toolsor something like
--with-clang-format. For now we have to do the entire thing by ourselves.
Some instructions were taken from Clang's getting started page:
Getting LLVM + Clang
$ svn co http://llvm.org/svn/llvm-project/llvm/trunk llvm $ cd llvm/tools $ svn co http://llvm.org/svn/llvm-project/cfe/trunk clang $ cd ../.. $ cd llvm/tools/clang/tools $ svn co http://llvm.org/svn/llvm-project/clang-tools-extra/trunk extra $ cd ../../../.. $ cd llvm/projects $ svn co http://llvm.org/svn/llvm-project/compiler-rt/trunk compiler-rt $ cd ../..
Building LLVM + Clang
$ ./llvm/configure $ makeIn my case, make didn't succeed, it takes forever and it fails somewhere after building clang-format but that is ok. clang-format was built and I wasn't planning to install llvm/clang from source either, I am fine with Xcode/brew stuff :p
Installing clang-formatIf it is not clear where makeput all compiled stuff we can always use find:
$ find . -name "clang-format" ./Release+Asserts/bin/clang-format ./tools/clang/tools/clang-formatWe need to copy clang-format command from above location to somewhere in our
PATHor make an alias. Also we want to install git-clang-format and maybe other scripts.
# copy clang-format command to your $PATH $ cp ./Release+Asserts/bin/clang-format /somewhere/in/your/PATH # install (copy) git-clang-format subcommand to your $PATH $ cd ./tools/clang/tools/clang-format $ cp git-clang-format ~/.bin
Using clang-format commandNow, lets say we are inside a directory which contains c/cpp/objc sources which we want to reformat. We simply create a
.clang-formatfile which should be of the form:
Key: Value Key: Value Key: Value Key: ValueAnd then we would run
clang-format file.cSome commands to know more about the command and keys available:
# dump all configuration keys clang-format -dump-config clang-format -dump-config style=webkit # help clang-format --help clang-format --help-list-hidden # format a file (it will read .clang-format file if available) clang-format filename.c # format a file with a explicit style clang-format -style=google filename.cCheck clang's official style documentation page for more info.
Using it with gitSince we installed git-clang-format file to our
PATH, if we are in a git repository, we can do:
git clang-formatAnd it will reformat all staged code, pretty awesome!
Are you wondering where did clang-format subcommand come from?! Answer: custom git subcommands are simply executables in the
PATHand its name should have the "git-" prefix and should not have extension.
Hope this info is helpful to somebody :)