如何使用clang-format切换并强制块注释的两种格式化风格?
用clang-format切换块注释风格的实现方案
我刚好研究过clang-format对块注释的格式化规则,要实现你要的两种风格切换,关键是调整两个核心配置项,下面分情况详细说明:
切换到格式化风格(1):统一为 /** * ... */
要让所有块注释都带上开头的*和空格,你需要在clang-format的配置文件(比如.clang-format)里设置以下参数:
# 块注释使用带星号的风格 BlockCommentStyle: Starred # 确保星号和注释内容之间有空格 SpacesInBlockComments: true # 开启注释自动修复(默认是true,但若被关闭需手动打开) FixComments: true
配置好后,运行clang-format处理你的代码:
clang-format -i your_source_file.cpp
处理后你的代码会变成:
/** * Starting from formatting style (1). */ void foo(); /** * Starting from formatting style (2). */ void bar();
切换到格式化风格(2):统一为 /** ... */
要移除块注释开头多余的*,只需调整BlockCommentStyle为默认值,配置如下:
# 使用默认块注释风格,不会自动添加开头星号 BlockCommentStyle: Default # 开启注释自动修复 FixComments: true
同样运行clang-format命令后,代码会被转换成:
/** Starting from formatting style (1). */ void foo(); /** Starting from formatting style (2). */ void bar();
补充说明
BlockCommentStyle的可选值有三个:Default(默认,不强制星号开头)、Starred(强制每行(包括第一行内容前)加星号)、BlankLines(在块注释的星号行之间添加空行,针对多行注释场景)- 确保你的clang-format版本足够新(建议10+),老版本可能不支持
BlockCommentStyle这个参数
内容的提问来源于stack exchange,提问作者Tom de Geus
相关产品推荐
相关产品推荐

