5

我有以下 .cpp 文件:

////////////////////////////////////////////////////////////////////////////////
void call_long_function_name(bool) {}
void sf(bool) {}
int main() {
  bool test = true;
  if (test) { call_function_name(test); }
  if (test) { sf(test); }
  return 0;
}

(斜线分隔 80 个字符)。使用以下配置文件,clang-format 建议:

////////////////////////////////////////////////////////////////////////////////
void call_long_function_name(bool) {}
void sf(bool) {}
int main() {
  bool test = true;
  if (test) { 
    call_function_name(test); 
  }
  if (test) { 
    sf(test); 
  }
  return 0;
}

即使在文件中,我也允许简短的 if 语句放在一行中。

  • 我是否设置了错误的选项?

  • 我可以使用哪些选项来最大程度地减少浪费的垂直空间?

Clang-format 的 .clang-format 文件

BasedOnStyle: Google
AccessModifierOffset: -1
AlignEscapedNewlinesLeft: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortFunctionsOnASingleLine: true
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackParameters: true
BreakBeforeBinaryOperators: true
BreakBeforeBraces: Attach
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: true
ColumnLimit: 80
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 2
ContinuationIndentWidth: 0
Cpp11BracedListStyle: true
DerivePointerBinding: true
IndentCaseLabels: true
IndentFunctionDeclarationAfterType: true
IndentWidth: 2
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
PointerBindsToType: true
SpaceAfterControlStatementKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInAngles:  false
Standard: Cpp11
TabWidth: 2
UseTab: Never
4

2 回答 2

9

Newer versions of clang-format have an additional option "AllowShortBlocksOnASingleLine", which controls this behavior.

于 2014-06-03T08:13:16.640 回答
6

似乎只有在省略括号clang-format时才应用该选项。AllowShortIfStatementsOnASingleLine我测试了以下内容:

void call_long_function_name(bool) {}
void call_long_super_duper_long_really_really_long_way_long_function_name(bool) {}
void sf(bool) {}
int main() {
  bool test = true;
  if (test) 
    call_function_name(test);
  if (test)
    sf(test);
  if (test)
    call_long_super_duper_long_really_really_long_way_long_function_name(test);
  if (test) {
    return 0;
  }
  return 0;
}

并得到:

void call_long_function_name(bool) {}
void call_long_super_duper_long_really_really_long_way_long_function_name(
bool) {}
void sf(bool) {}
int main() {
  bool test = true;
  if (test) call_function_name(test);
  if (test) sf(test);
  if (test)
    call_long_super_duper_long_really_really_long_way_long_function_name(test);
  if (test) {
    return 0;
  }
  return 0;
}
于 2014-03-19T16:43:33.453 回答