Clang编译器包中带了一个代码格式化工具,叫做clang-format,功能强大。
可以使用HomeBrew在macOS系统下安装clang-format:
brew install clang-format
clang-format自带了几种代码格式化风格,分别是:LLVM, Google, Chromium, Mozilla, WebKit. 这些风格可以通过命令行选项-style
指定,比如需要谷歌风格,可以指定:-style=Google
。
默认情况下,clang-format还可以从.clang-format
文件读取风格,这相当于调用clang-format的时候,使用选项-style=file
。你可以以默认的风格为基础来定制自己的风格:
clang-format -style=Mozilla -dump-config > .clang-format
上面的命令打印出默认的Mozilla代码风格,并把打印出的内容重定向到.clang-format
文件。
从文档ClangFormatStyleOptions上看,clang-format的自定义选项挺好多,不太好选择。有一个网站Clang Format Configurator可以帮你在线编辑和预览clang-format的选项,然后下载配好的内容。
如果你使用Vim编辑器的话,可以到vim-clang-format这边下载插件。
StackOverflow的帖子Best C++ Code Formatter/Beautifier记录有除clang-format之外的其他代码格式化工具。
git-clang-format
LLVM的包里面提供了一个git-clang-format脚本,这个脚本可以用来格式化git仓库中已经stage了的改动。