What is ClangFormat?
ClangFormat tools for formatting code.
How to install ClangFormat?
sudo apt install clang-format
How to use ClangFormat?
As a separate command
Common commands are as follows:
$ ## 从标准输入输入,输出到标准输出
$ clang-format
$
$ ## 从文件输入,输出到标准输出
$ clang-format main.cc
$
$ ## 从文件输入,输出到原文件
$ clang-format main.cc -i
$
$ ## 将配置文件写入 .clang-format
$ clang-format -style=llvm -dump-config > .clang-format
$
$ ## 指名代码风格:LLVM,Google,Chromium,Mozilla,WebKit
$ clang-format -style=llvm main.cc
$
$ ## 指明代码风格,代码风格存储在当前目录或父目录的文件 .clang-format 或 _clang-format 中
$ clang-format -style=file main.cc
$
Use in Vim
1. Locate the directory where the file clang-format.py
dpkg -L clang-format | grep clang-format.py
2. configuration file .vimrc
Add the following in your .vimrc
function! Formatonsave()
let l:formatdiff = 1
pyf <path-to-this-file>/clang-format.py
endfunction
autocmd BufWritePre *.h,*.cc,*.cpp call Formatonsave()
Explanation :
- The contents indicated above, when using Vim save documents, format code
- Above
<path-to-this-file>
refers to the directory clang-format.py let l:formatdiff = 1
Formatting means only modified portions may belet l:lines = "all"
substituted, represents all of the content formatted- In Ubuntu 18.04 LTS, the default version of clang-format for clang-format-6.0, clang-format-6.0 of clang-format.py using Python 3, and Ubuntu 18.04 LTS default Python version Python 2.7, so it is necessary the above pyf changed py3f