clang-format 未根据其配置文件格式化 C 头文件 (.h)

clang-format is not formatting C header files (.h) according to its config file

提问人:Newb 提问时间:10/5/2023 更新时间:10/10/2023 访问量:170

问:

我正在运行 GNU/Linux 机器x86_64并使用 neovim 中的 clang-format 来格式化我的 C 代码。此外,我正在使用我自己的 .clang 格式配置文件,该文件主要基于 Mozilla 的样式。

我对配置文件所做的更改直接转换为我格式化的源文件 (.c) 文件,但由于某种原因,头文件 (.h) 不遵循我的 .clang 格式配置文件中指定的格式样式。它说每次我尝试格式化头文件时都成功运行了 clang-format,但格式本身与 .clang 格式文件中指定的没有任何内容,我做错了什么?

请记住,当我格式化源文件时,所有内容都按照 .config-format 中指定的方式完美格式化。

编辑: 我正在运行带有这些参数的clang格式可执行文件(我的.config格式的路径)

clang-format --style=文件:/home/myusername/.config/formatting/.clang-format

c 头文件 neovim clang-format

评论

1赞 John Doe 10/10/2023
您是否尝试过将该选项添加到您的命令中?-iclang-format
0赞 Newb 10/10/2023
@JohnDoe 当从终端命令行运行时,这确实有效,它会根据我的配置文件格式化我的头文件,但由于某种原因无法在 neovim 中工作,无论如何我都会接受这个作为答案。另外,为什么它只在启用 -i 标志的情况下工作?
0赞 John Doe 10/10/2023
我发布了一个答案,这很奇怪;不在 neovim 中工作,我没有这方面的经验,所以不幸的是,我不能说是否有特别的东西搞砸了clang-format

答:

0赞 Jason 10/5/2023 #1

我不认为这是如何运作的。从:style=fileclang-format --help

--style=<string>           - Coding style, currently supports:
                               LLVM, GNU, Google, Chromium, Microsoft, Mozilla, WebKit.
                             Use -style=file to load style configuration from
                             .clang-format file located in one of the parent
                             directories of the source file (or current
                             directory for stdin).
                             Use -style="{key: value, ...}" to set specific
                             parameters, e.g.:
                               -style="{BasedOnStyle: llvm, IndentWidth: 8}"

我相信这实际上是默认行为。它基本上搜索父目录,直到找到一个名为 .基本上:style=file.clang-format

./.clang-format
../.clang-format
../../.clang-format

如果将 移动到当前工作目录的父目录,它将起作用。.clang-format

评论

0赞 Newb 10/5/2023
当我格式化源文件时,格式化已经起作用,但在尝试格式化 .h 文件时使用默认(我认为)格式。来自 clang-format 文档:“使用 -style=file:<format_file_path> 时,每个输入文件的 clang-format 将使用位于 <format_file_path> 的格式化文件。路径可以是绝对路径,也可以是相对于工作目录的路径。
1赞 John Doe 10/10/2023 #2

从命令行运行以格式化文件时,必须使用该选项。clang-format-i

这表示要执行,因此,使用新格式覆盖文件。clang-formatinplace edit

在没有 的情况下调用将格式化文件,但不会将其保存在任何地方clang-format-i