如何以clang格式包装struct初始值设定项?

ide*_*n42 6 c clang-format

在运行clang-format之前,请看以下示例:

struct ApplicationState app_state = {
    .signal = {
        .use_crash_handler = true,
        .use_abort_handler = true,
    },
    .exit_code_on_error = {
        .python = 0,
    }
};
Run Code Online (Sandbox Code Playgroud)

运行后,clang-format适用如下:

struct ApplicationState app_state = {.signal =
                                             {
                                                     .use_crash_handler = true,
                                                     .use_abort_handler = true,
                                             },
                                     .exit_code_on_error = {
                                             .python = 0,
                                     }};
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以在大括号后,struct成员之前添加换行符,因此更像第一个示例,而不像第二个示例?

ide*_*n42 8

目前clang-format没有一个有用的方法来控制这个(从 11.0 版开始)

虽然BreakBeforeBinaryOperators: All确实强制包装(参见@eric-backus 的回答),但它也会影响许多其他地方的格式,与结构声明无关。

但是,您可以通过使用尾随逗号来解决此问题。


前:

struct ApplicationState app_state = {.signal =
                                             {
                                                     .use_crash_handler = true,
                                                     .use_abort_handler = true,
                                             },
                                     .exit_code_on_error = {
                                             .python = 0,
                                     }};
Run Code Online (Sandbox Code Playgroud)

后:


struct ApplicationState app_state = {
    .signal = {
        .use_crash_handler = true,
        .use_abort_handler = true,
    },
    .exit_code_on_error = {
        .python = 0,
    },
};
/*   ^ notice trailing comma on the second last line! */
Run Code Online (Sandbox Code Playgroud)