Force member initialization in static const struct in c

Viewed 77

I am using a structs for storing different configurations and I would like to force the initialization of all members. 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.

Any tips about how to achieve this?

Since I would like to use designated initializers, -Wmissing-field-initializers does not work in this case. 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,
};
1 Answers

There's no particularly elegant way to do this programmatically. Best bet is to use a static initializer tool. (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.)

With pure standard C, well... Since this struct won't have any padding, I suppose you could cook up something fairly ugly like this:

#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."

Related