问题
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
)
回答1:
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.
回答2:
The following example code defines a struct in what I consider a more C++ way (no need for typedef) and uses a constructor to solve your problem:
#include <iostream>
#define VERSION_DATE "TODAY"
#define VERSION_REVISION "0.0.1a"
struct infos {
int lots_of_ints;
/* ... lots of other members */
const char *build_date;
const char *build_version;
infos() :
build_date(VERSION_DATE),
build_version(VERSION_REVISION)
{}
};
static const infos s_infos;
const infos *get_info()
{
return &s_infos;
}
int main() {
std::cout << get_info()->build_date << std::endl;
std::cout << get_info()->build_version << std::endl;
return 0;
}
回答3:
I believe this was added as a feature in C99, but has never been a standard feature in C++.
However, some compilers probably offer it as a non-standard language extension.
来源:https://stackoverflow.com/questions/5790534/static-structure-initialization-with-tags-in-c