我想在我的项目中添加 clang-format 工具以遵循特定的编码风格。我已经有一个项目和 makefile。我应该如何使用 makefile 将 clang-format 工具集成到我的项目中?
首先,您的道路上需要
clang-format
和 clang-format-diff.py
。
这是一个 python 脚本,它递归地格式化目录中的所有 c/c++ 源文件/头文件:
import os
cpp_extensions = (".cpp", ".cxx", ".c++", ".cc", ".cp", ".c", ".i", ".ii", ".h", ".h++", ".hpp", ".hxx", ".hh", ".inl", ".inc", ".ipp", ".ixx", ".txx", ".tpp", ".tcc", ".tpl")
for root, dirs, files in os.walk("src"):
for file in files:
if file.endswith(cpp_extensions):
os.system("clang-format -i -style=file " + root + "/" + file)
我有一个具有自定义样式的
.clang-format
文件,因此有 -style=file
参数。 -i
用于就地编辑。
这可能不是最Pythonic的方式,但它对我有用。你可以在 bash 中重写它。
您可以将
format
目标添加到您的 makefile 中,如下所示:
format:
python the_script.py
如果你愿意,你可以像这样只格式化 git 中的脏文件(如here所述):
format:
git diff -U0 HEAD^ | clang-format-diff.py -i -p1