簡介
- ClangFormat 是一個規范代碼的工具
- ClangFormat 支持的語言有:C/C++/Java/JavaScript/Objective-C/Protobuf/C#
- ClangFormat 支持的規范有:LLVM,Google,Chromium,Mozilla 和 WebKit
測試環境
- Ubuntu 18.04 LTS
- clang-format-6.0
安裝
$ sudo apt install clang-format
使用
命令行使用
常用命令如下:
- 預覽規范后的代碼
$ clang-format main.cc
- 直接在原文件上規范代碼
$ clang-format -i main.cc
- 顯示指明代碼規范,默認為 LLVM
$ clang-format -style=google main.cc
- 將代碼規范配置信息寫入文件 .clang-format
$ clang-format -dump-config > .clang-format
- 使用自定義代碼規范,規范位於當前目錄或任一父目錄的文件 .clang-format 或 _clang-format 中(如果未找到文件,使用默認代碼規范)
$ clang-format -style=file main.cc
在 Vim 中使用
- 查找文件 clang-format.py 所在的目錄:
$ dpkg -L clang-format | grep clang-format.py
- 在 .vimrc 中加入以下內容
function! Formatonsave()
let l:formatdiff = 1
py3f <path-to-this-file>/clang-format.py
endfunction
autocmd BufWritePre *.h,*.cc,*.cpp call Formatonsave()
說明:
- 上述的內容表示:當使用 Vim 保存文件時,會按照當前目錄 或 任一父目錄的文件 .clang-format 或 _clang-format 指定的規范來規范代碼(如果未找到文件,使用默認代碼規范)
- 上述
<path-to-this-file>
指的是 clang-format.py 的目錄 let l:formatdiff = 1
的意思是只規范修改過的部分,可以用let l:lines = "all"
取代,表示規范所有的內容- 在 Ubuntu 18.04 LTS 下,clang-format 的默認版本為 clang-format-6.0,clang-format-6.0 的 clang-format.py 使用的是 Python 3,而 Ubuntu 18.04 LTS 默認的 Python 版本為 Python 2.7,所以上面使用的是 py3f 而不是 pyf