前一段时间因工作需要参与了一个开源项目,在向github提交代码后提示格式校验失败。
项目的管理者告知,要想修改的代码能入库需要使用Clang-Format校验。
需要使用下面的命令对上次的修改重新格式化下:
git show HEAD | clang-format-diff-3.9 -p 1 -style=file -i
通过调查了解到此开源项目是使用Clang Tools来管理代码的格式,可使用ClangCheck来校验代码的格式问题,使用clang-format来格式化代码。
我们为什么不可以在IDE中直接集成Clang工具自动格式化代码吗?
我使用的IDE是VIM,我相信如此强大的工具必然能实现此功能,在官网http://clang.llvm.org/docs/ClangTools.html 我如愿的找到了资料。
首先需要安装clang-format
sudo apt-get install clang-format-3.9
ln -s /usr/bin/clang-format-3.9 /usr/bin/clang-format
然后
cd ~/sbin;
wget https://raw.githubusercontent.com/llvm/llvm-project/master/clang/tools/clang-format/clang-format.py
再修改~/.vimrc来配置clang-format.py使用方法,增加以下内容
"""""""""""""""""""""""""""""""""""""""""""""""
" Seting clang-format
"""""""""""""""""""""""""""""""""""""""""""""""
map <C-F> :pyf ~/sbin/clang-format.py<cr>
imap <C-F> <c-o>:pyf ~/sbin/clang-format.py<cr>
function! Formatonsave()
let l:formatdiff = 1
pyf ~/sbin/clang-format.py
endfunction
autocmd BufWritePre *.c,*.h,*.cc,*.cpp call Formatonsave()
这样当编辑*.c,*.h,*.cc,*.cpp时,会自动格式化,也可以是使用ctrl+f格式化一行或者选中的区域。
clang-format默认是使用llvm格式,用户也可根据需要配置格式化参数。
可行在工作路径的最上层路径,使用以下方式生成.clang-format文件,然后可根据需要修改参数。
clang-format -style=llvm -dump-config > .clang-format
-style=xxxx 可使用LLVM, Google, Chromium, Mozilla, WebKit