I have a header called filepaths.h which defines a number of static variables:
#ifndef FILEPATHS_H
#define FILEPATHS_H
class FilePaths {
public:
static QString dataFolder();
static QString profileFolder();
private:
static QString dataFolder_;
static QString profileFolder_;
};
}
#endif // FILEPATHS_H
And I have an associated filepaths.cpp which initially looked like this:
#include "FilePaths.h"
QString FilePaths::dataFolder() {
return dataFolder_;
}
QString FilePaths::profileFolder() {
return profileFolder_;
}
However that didn’t work – I got an “unresolved symbol error” linker error on all the static variables. So I’ve added these variables to the C++ file in this way:
#include "FilePaths.h"
QString FilePaths::dataFolder_ = "";
QString FilePaths::profileFolder_ = "";
QString FilePaths::dataFolder() {
return dataFolder_;
}
QString FilePaths::profileFolder() {
return profileFolder_;
}
And this works, however I don’t understand why.
Why do these static variables need to be defined twice? Or maybe I’m not defining them but initializing them? But still why does it need to be done? Or should I write my class differently?
One is a definition, the other is a declaration. The difference is that declarations can appear multiple times, and for variables not in a class, maybe never at all, whereas definitions can appear once and only once.
The reasons for needing separate declarations and definitions is archaic history, the kind of thing where it basically doesn’t have to be that way at all but it is that way so that C++ is compatible with C, which was designed to be compiled in the 1970s.