10

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!

1
  • 3
    Note that elaborated type specifiers (struct timespec) are pretty much not needed in C++. Just write timespec. Commented Aug 22, 2012 at 19:01

2 Answers 2

24

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I'm pretty noob in C++, I've heard, I should declare classes in classname.h file and define them in classname.c file. And so I will be able to include .h file into my programs as many times as I need, but when and how do I use .c file? I'm using a g++ compiler...
.c is for C source files, don't use it for C++. Use either .cc or .cpp for C++ source files (.cc is generally preferred on Linux, .cpp is generally preferred on Windows, but either will do). In general, a declaration says "here is the name of something, but that's all I know about it" (e.g. the name of a class or function). A definition says "here is the name of something and what it is", e.g. class members, function body, variable value, etc.
yes, I get this, thank you! I declare my class in .h file, then I define it in .cpp file. Then I include .h to my program. Now the question: what should I do with my .cpp file? How do I use it? Should I write it somewhere here g++ main.cpp -o main? I'm using g++ on Linux.
When compiling put all your .cpp files in the list. Do not put headers. ex. g++ main.cpp myclass.cpp -o main
@Kolyunya if you want to keep the extension short you can use an UPPER-case .C extension... more on extensions in this answer: stackoverflow.com/a/3223792 and other answers on that page or just google "c++ source extensions"
0

Declare the variable as a static variable inside a function and make that function return the reference to the variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.