You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置clang-format让C++属性后换行定义函数?

如何让clang-format在C++ [[deprecated]]属性后强制换行?

我在代码中使用了[[deprecated]]属性,但未找到让C++属性后换行的clang-format配置方法,希望do_not_use()函数的定义能放在[[deprecated]]属性的下一行。

当前代码格式:

[[deprecated("Will be removed in version 2.3.0 as it doesn't support "
             "multi-threading processing. "
             "Use mt_process_info() instead")]] void
do_not_use()
{
    std::cout << "This function should not be used" << std::endl;
}

期望代码格式:

[[deprecated("Will be removed in version 2.3.0 as it doesn't support "
             "multi-threading processing. "
             "Use mt_process_info() instead")]]
void do_not_use()
{
    std::cout << "This function should not be used" << std::endl;
}

我的.clang-format配置:

Language: Cpp
Standard: c++20
AccessModifierOffset: 0
AlignEscapedNewlines: Right
AlignOperands: true
AllowShortFunctionsOnASingleLine: None
BreakBeforeBraces: Custom
BraceWrapping:
    AfterCaseLabel: true
    AfterClass: true
    AfterControlStatement: true
    AfterEnum: true
    AfterFunction: true
    AfterNamespace: true
    AfterStruct: true
    BeforeCatch: true
    BeforeElse: true
    IndentBraces: false
    SplitEmptyFunction: true
ColumnLimit: 100
Cpp11BracedListStyle: true
IncludeBlocks: Regroup
IndentAccessModifiers: true
IndentCaseLabels: true
IndentWidth: 4
PointerAlignment: Left
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: true
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
UseTab: Never

我尝试调整AttributeMacros和StatementAttributeLikeMacros配置,但未解决问题。


解决方案

在你的.clang-format配置中添加BreakAfterAttributes: All选项,该选项会强制在所有属性块之后换行,正好满足你的需求。

修改后的配置片段:

Language: Cpp
Standard: c++20
BreakAfterAttributes: All
# 其余原有配置保持不变...

添加该配置后,clang-format会自动将属性后的函数定义换行到下一行,与你期望的格式一致。

内容的提问来源于stack exchange,提问作者CleanCoder265

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 07:55:38