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
)
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.
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.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With