格式化程序使用clang-format,代码风格除了预定义的LLVM, GNU, Google, Chromium, Microsoft, Mozilla规则,还可以用file定义的风格。
这里我们基于谷歌的规则进行一些修改成我们项目自己风格。
clang-format --style=Google --dump-config > .clang-format
.clang-format包含了规则。比如谷歌风格缩进是2个空格,我们改成熟悉的4个文件
编辑.clang-format,IndentWidth:的变量设置为4。AccessModifierOffset把-1设置为-3,这个主要是设置cpp的public,private,pretected相对于函数的向左相隔距离。
根据git提交特性,可以设置commit前的钩子脚本,这个钩子脚本完成对代码的格式化,
首先可以设置git config hooks.clangformatstyle file。这样规则文件使用工程内的.clang-format文件
我们使用github有大婶开源的hook脚本。
git clone https://github.com/andrewseidl/githook-clang-format.git
cp githook-clang-format/clang-format.hook {你的工程文件夹}/.git/hooks/pre-commit
#钩子函数的逻辑就是去读取本次代提交的差异所在的文件,然后对文件进行clang-format操作。
#!/bin/bash
STYLE=$(git config --get hooks.clangformat.style)
if [ -n "${STYLE}" ] ; then
STYLEARG="-style=${STYLE}"
else
STYLEARG=""
fi
format_file() {
file="${1}"
if [ -f $file ]; then
clang-format -i ${STYLEARG} ${1}
git add ${1}
fi
}
case "${1}" in
--about )
echo "Runs clang-format on source files"
;;
* )
for file in `git diff-index --cached --name-only HEAD | grep -iE '\.(cpp|cc|h|hpp)$' ` ; do
format_file "${file}"
done
;;
esac
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。