Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static structure initialization with tags in C++

I've searched stackoverflow for an answer but I cannot get something relevant.

I'm trying to initialize a static structure instance with initial values by specifying their tags, but I get an error at compilation time:

src/version.cpp:10: error: expected primary-expression before ‘.’ token

Here's the code:

// h
typedef struct
{
    int lots_of_ints;
    /* ... lots of other members */
    const char *build_date;
    const char *build_version;
} infos;

And the faulty code:

// C

static const char *version_date = VERSION_DATE;
static const char *version_rev  = VERSION_REVISION;

static const infos s_infos =
{
   .build_date    = version_date, // why is this wrong? it works in C!
   .build_version = version_rev
};

const infos *get_info()
{
    return &s_infos;
}

So the basic idea is to bypass the "other members" initialization and only set the relevant build_date and build_version values. This used to work in C, but I can't figure out why it won't work in C++.

Any ideas?

edit:

I realize this code looks like simple C, and it actually is. The whole project is in C++ so I have to use C++ file extensions to prevent the makefile dependency mess ( %.o: %.cpp )

like image 761
Gui13 Avatar asked Apr 26 '11 12:04

Gui13


People also ask

How to initialize a static variable in C?

In C, static variables can only be initialized using constant literals. For example, following program fails in compilation. If we change the program to following, then it works without any error.

How to initialize a structure variable in C language?

C language supports multiple ways to initialize a structure variable. You can use any of the initialization method to initialize your structure. In C, we initialize or access a structure variable either through dot . or arrow -> operator.

How to initialize struct members in C++?

The casting to the type of the struct is the necessary step to compile the program. Another method to initialize struct members is to declare a variable and then assign each member with its corresponding value separately.

Is there a way to initialize structure data-elements with static keyword?

So your current code attempts using the static keyword won't work. Additionally you can't initialize structure data-elements at the point of declaration like you've done. Instead, you could do the following using designated initializers:


1 Answers

The feature you are using is a C99 feature and you are using a C++ compiler that doesn't support it. Remember that although C code is generally valid C++ code, C99 code isn't always.

like image 112
NVade Avatar answered Oct 06 '22 23:10

NVade