简体   繁体   English

static 中的强制成员初始化 c 中的 const 结构

[英]Force member initialization in static const struct in c

I am using a struct s for storing different configurations and I would like to force the initialization of all members.我正在使用struct s 来存储不同的配置,并且我想强制初始化所有成员。 I mean not let the compiler do it (to zero), but the progammer explizitly.我的意思是不要让编译器这样做(为零),而是让程序员明确地这样做。

A compiler error would be best but a warning would be fine as well.编译器错误最好,但警告也可以。 I am using Segger clang for arm.我将 Segger clang 用于 arm。

Any tips about how to achieve this?关于如何实现这一目标的任何提示?

Since I would like to use designated initializers, -Wmissing-field-initializers does not work in this case.由于我想使用指定的初始化程序, -Wmissing-field-initializers在这种情况下不起作用。 See: Docs请参阅:文档

typedef struct{
    int option_1,
    int option_2,
    ....
} config_t;

// this is fine
const config_t config_1 = {
    .option_1 = 10,
    .option_2 = 20,
};

// this should generate a warning
const config_t config_1 = {
    .option_2 = 20,
};

There's no particularly elegant way to do this programmatically.以编程方式执行此操作没有特别优雅的方法。 Best bet is to use a static initializer tool.最好的办法是使用 static 初始化工具。 (There's for example a MISRA-C:2012 rule that can be checked for, requiring that all elements of a struct must be initialized explicitly.) (例如,可以检查 MISRA-C:2012 规则,要求结构的所有元素都必须显式初始化。)

With pure standard C, well... Since this struct won't have any padding, I suppose you could cook up something fairly ugly like this:使用纯标准 C,嗯......由于这个结构不会有任何填充,我想你可以像这样制作一些相当难看的东西:

#define CONFIG_INIT_LIST1 10, 20
#define CONFIG_INIT_LIST2 10

_Static_assert(sizeof (int[]){CONFIG_INIT_LIST1} == sizeof (config_t),
               "CONFIG_INIT_LIST1 wrong number of initializers.");
_Static_assert(sizeof (int[]){CONFIG_INIT_LIST2} == sizeof (config_t),
               "CONFIG_INIT_LIST2 wrong number of initializers.");

// this is fine
const config_t config_1 = {
    CONFIG_INIT_LIST1
};

const config_t config_2 = {
    CONFIG_INIT_LIST2
};

This gives the compiler error这会导致编译器错误

error: static assertion failed: "CONFIG_INIT_LIST2 wrong number of initializers."错误:static 断言失败:“CONFIG_INIT_LIST2 初始化器数量错误。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM