如何配置clang-format使switch/case多语句保持单行?
问题:clang-format 强制拆分多语句case为多行的解决办法
原本紧凑易读的3行switch/case代码:
case 0xfc: printf("CM $%02x%02x",code[2],code[1]); opbytes = 3; break; case 0xfd: printf("CALL $%02x%02x",code[2],code[1]); opbytes = 3; break; case 0xfe: printf("CPI #$%02x",code[1]); opbytes = 2; break;
经clang-format格式化后被拆分为12行:
case 0xfc: printf("CM $%02x%02x", code[2], code[1]); opbytes = 3; break; case 0xfd: printf("CALL $%02x%02x", code[2], code[1]); opbytes = 3; break; case 0xfe: printf("CPI #$%02x", code[1]); opbytes = 2; break;
仅包含两个语句的case格式化后能保持单行:
case 0xf1: printf("POP PSW"); break;
但添加第三个语句后就会被拆分换行。当前.clang-format配置如下:
AllowShortBlocksOnASingleLine: "true" AllowShortCaseLabelsOnASingleLine: "true" AllowShortFunctionsOnASingleLine: All AllowShortIfStatementsOnASingleLine: WithoutElse BreakBeforeBraces: Allman ColumnLimit: 150
代码未超出150列限制,使用Apple Clang 17.0.6版本,需如何配置阻止这种格式化行为?
解决方案
在.clang-format中添加AllowShortStatementsOnASingleLine: "Always"配置项即可:
AllowShortBlocksOnASingleLine: "true" AllowShortCaseLabelsOnASingleLine: "true" AllowShortFunctionsOnASingleLine: All AllowShortIfStatementsOnASingleLine: WithoutElse AllowShortStatementsOnASingleLine: "Always" # 新增关键配置 BreakBeforeBraces: Allman ColumnLimit: 150
配置说明
AllowShortCaseLabelsOnASingleLine仅控制case标签和第一条语句是否同行,无法覆盖多语句场景。AllowShortStatementsOnASingleLine: "Always"允许将多个短语句合并到同一行,正好满足多语句case保持单行的需求。- 代码未触发
ColumnLimit限制,因此无需调整列宽参数。
内容的提问来源于stack exchange,提问作者canersevdiceginibekleyenoglu
相关产品推荐
相关产品推荐

