C++ Initializing static const structure variable
30,925
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.
Comments
-
Kolyunya over 3 years
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!
-
Kolyunya over 11 yearsI'm pretty noob in C++, I've heard, I should declare classes in
classname.h
file and define them inclassname.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... -
Adam Rosenfield over 11 years
.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. -
Kolyunya over 11 yearsyes, 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 hereg++ main.cpp -o main
? I'm using g++ on Linux. -
Aleks over 11 yearsWhen compiling put all your .cpp files in the list. Do not put headers. ex. g++ main.cpp myclass.cpp -o main
-
jave.web about 9 years@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"