How to rewrite C-struct designated initializers to C89 (resp MSVC C compiler)

DinGODzilla picture DinGODzilla · Mar 26, 2011 · Viewed 10.8k times · Source

guys, I've this problem:

Normally in C99 GCC (cygwin / MinGW / linux), there is dot-notation syntax for initializers in C struct.
Like this:

//HELP ME HOW TO REWRITE THIS (in most compact way) to MSVC
static struct my_member_t my_global_three[] = {
    {.type = NULL, .name = "one"},
    {.type = NULL, .name = "two"},
    {.type = NULL, .name = "three"},
};

Having my_memeber_t defined in header file as:

struct my_member_t {
    struct complex_type * type;
    char * name;
    int default_number;
    void * opaque;
};

I'm compiling linux code in MSVC 9.0 (Visual Studio 2008), on cygwin/MinGW this works ok.
BUT cl is unable to compile this (because of miserable C99 implementation): error C2059: syntax error : '.'

PROBLEM:
How to rewrite (many) global structs in a way that MSVC
(resp C89)can compile it?


Best regards and thanks for suggestions...

Answer

AnT picture AnT · Mar 26, 2011

Miserable C99 implementation? I don't think that C compiler in VC2008 even tries to implement C99. It might borrow some features, but it is really a C89/90 compiler.

Just drop the field name tags

static struct my_member_t my_global_three[] = {
    { NULL, "one"},
    { NULL, "two"},
    { NULL, "three"},
};

In this case it is easy, since the order of the initializers in the original code is the same as the order of fields in the struct. If the order was different, you'd have to rearrange them in the tagless C89/90 version.

And if it's really your my_member_t, then you should either declare the string pointer as const char * or stop initializing these members with string literals.