作为记录,对于那些对 Clang 和 LLVM 感兴趣的人来说,有一个替代解决方案。
clang-format 绝对可以帮助轻松高效地格式化现有源代码。它显式内置支持 5 种格式,即LLVM(默认)、Google、Chromium、Mozilla、WebKit。
使用 Google 样式格式化文件的简单方法是:
clang-format -style=Google -i filename
其中-i 表示就地修改,您可以尝试不使用此选项来预览更改。
要批量格式化现有的 C/C++ 代码,我们可以简单地使用如下命令:
find . -name "*.cc" | xargs clang-format -style=Google -i
除了上面列出的5种格式之外,其实还有其他样式,比如GNU(添加到revision 197138;可惜文档没有同步)。
请注意,clang-format 在项目中接受名为 .clang-format 或 _clang-format 的类 rc 文件,这是添加此类配置文件的最简单方法(如在clang-format的官方教程页面中说)是转储现有格式的配置,例如:
clang-format -style=Google -dump-config >.clang-format
您也可以使用BasedOnStyle 选项,因此配置文件可能如下所示:
---
BasedOnStyle: Chromium
PointerBindsToType: false
ObjCSpaceAfterProperty: true
...
使用.clang-format或_clang-format作为关键词在Github上搜索,还有其他示例;或者您可以参考this site 来帮助构建一个。
还集成了 IDE/编辑器,例如 Visual Studio(在目录 clang-format-vs)、Sublime、Emacs、Vim(都在目录 clang-format)。
另外 3 个提示:
对于 Emacs 集成(clang-format.el),我个人认为最好为clang-format-buffer 绑定密钥而不是clang-format-region。
-
对于Mac OSX homebrew 安装,使用brew install --with-clang, --with-lld, --with-python --HEAD llvm 可以获得clang-format 的支持,它的集成文件在$(brew --cache)/llvm--clang--svn-HEAD/tools/clang-format(奖励:那里甚至还有一个git-clang-format!!)。
clang-extra-tools 内还有其他精彩工具,例如 clang-modernize(用于“自动转换针对旧标准编写的 C++ 代码以使用最新 C++ 标准的功能,其中合适”),真的值得一试!