【问题标题】:Clang-format: how to format C struct initializer this wayClang-format:如何以这种方式格式化 C 结构初始化程序
【发布时间】:2021-01-11 14:55:00
【问题描述】:

我正在使用 linux 内核 .clang-format 作为参考,但这部分让我很困扰。

如何获得 clang-format 来格式化此代码

const struct my_struct hello = {.id = 0,
                                .modsmin = 10,
                                .modsmax = 20,
                                .strengthmin = 0,
                                .strengthmax = 100,
                                .color = COLOR_FOREGROUND };

到这里

const struct my_struct hello = {
    .id = 0,
    .modsmin = 10,
    .modsmax = 20,
    .strengthmin = 0,
    .strengthmax = 100,
    .color = COLOR_FOREGROUND
};

【问题讨论】:

    标签: c struct initializer clang-format


    【解决方案1】:

    查看documentation,似乎没有任何clang-format 样式选项可以满足您的需求。

    但是,您可以使用“comma-after-last-item”技巧。在最后一个指定的初始值设定项之后,最后一个右大括号之前放置一个逗号。我相信这仍然是有效的 C 代码。然后clang-format 会将每个初始化程序放在单独的行上,这会将缩进移回您要查找的内容。所以输出看起来像这样:

    const struct my_struct hello = {
        .id = 0,
        .modsmin = 10,
        .modsmax = 20,
        .strengthmin = 0,
        .strengthmax = 100,
        .color = COLOR_FOREGROUND,
    };
    

    这种行为在任何地方都没有记录(据我所知),所以我想它将来可能会改变。但是这种行为已经存在很多年了,很多版本的clang-format,所以我认为依赖它是合理的。

    【讨论】:

      猜你喜欢
      • 2018-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-01
      • 2014-11-17
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多