Kolyunya Kolyunya - 1 year ago 160
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 {
static const struct timespec UPDATE_TIMEOUT = { 10 , 10 };


Getting this error:

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

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

How do I initialize it? Thanks!

Answer Source

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

// Header file
class Game {
        // 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download