首页 > 解决方案 > C++中结构数组的clang格式奇怪的缩进

问题描述

我正在尝试使用 clang-format(在 VS 代码中)来格式化我的 C++ 文件并将其配置为我喜欢的样式。对于结构数组(对于 getopts),它添加了大量额外的空格并弄乱了大括号包装:

我将在此查询的末尾附加我的 .clang 格式

这是我希望我的数组出现的方式:

int main()
{
  const struct option longopts[]=
  {
    {"log-file", required_argument, 0, LOGFILE},
    {"log-level", required_argument, 0, LOGLEVEL},
    {nullptr, 0, nullptr, 0}
  };
}

以下是它的实际显示方式:

int main()
{
  const struct option longopts[] =
      {
          {"log-file", required_argument, 0, LOGFILE},
          {"log-level", required_argument, 0, LOGLEVEL},
          {nullptr, 0, nullptr, 0}};
}

我的 .clang 格式文件包含:

BasedOnStyle: LLVM
IndentWidth: 2
AlignAfterOpenBracket: Align
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortFunctionsOnASingleLine: true
AllowShortBlocksOnASingleLine: true
BinPackParameters: true
BreakBeforeBraces: Custom
BraceWrapping:
  AfterClass: true
  AfterControlStatement: true
  AfterEnum: true
  AfterFunction: true
  AfterNamespace: true
  AfterObjCDeclaration: true
  AfterStruct: true
  AfterUnion: true
  AfterExternBlock: true
  BeforeCatch: true
  BeforeElse: true
  IndentBraces: false
  SplitEmptyFunction: false
  SplitEmptyRecord: false
  SplitEmptyNamespace: false
BreakConstructorInitializers: AfterColon
ColumnLimit: 0
ConstructorInitializerAllOnOneLineOrOnePerLine: false
IndentCaseLabels: true
KeepEmptyLinesAtTheStartOfBlocks: true
NamespaceIndentation: All
PointerAlignment: Right
SortIncludes: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: Never
SpaceInEmptyParentheses: false
SpacesInContainerLiterals: false
SpacesInAngles: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
UseTab: Never

欢迎任何解决方案!

标签: c++code-formattingclang-format

解决方案


我不确定是否可以实现您想要的,但有时最简单的方法是稍微修改源文件以帮助使用 clang-format 实用程序。首先,您需要在ContinuationIndentWidth: 2格式文件中添加一个选项。然后在数组中的最后一项之后添加一个逗号:

{nullptr, 0, nullptr, 0}, // <---

最后将第一个大括号移动到与数组名称相同的行上。生成的文件将如下所示:

int main()
{
  const struct option longopts[] = {
    {"log-file", required_argument, 0, LOGFILE},
    {"log-level", required_argument, 0, LOGLEVEL},
    {nullptr, 0, nullptr, 0},
  };
}

运行 clang-format 将保持原样。在 LLVM 快照构建的 clang-format 上进行了测试LLVM-9.0.0-r351376-win64.exe


推荐阅读