Kolyunya Kolyunya - 3 months ago 22
C++ Question

C++ Initializing static const structure variable

I'm trying to add a static constant variable to my class, which is an instance of a structure. Since it's static, I must initialize it in class declaration. Trying this code

class Game {
public:
static const struct timespec UPDATE_TIMEOUT = { 10 , 10 };

...
};


Getting this error:


error: a brace-enclosed initializer is not allowed here before '{'
token

error: invalid in-class initialization of static data member of non-integral type 'const timespec'


How do I initialize it? Thanks!

Answer

Initialize it in a separate definition outside the class, inside a source file:

// Header file
class Game {
    public:
        // Declaration:
        static const struct timespec UPDATE_TIMEOUT;
    ...
};

// Source file
const struct timespec Game::UPDATE_TIMEOUT = { 10 , 10 };  // Definition

If you include the definition in a header file, you'll likely get linker errors about multiply defined symbols if that header is included in more than one source file.