I have an header file header:
#ifndef __DATABASE_HELPER_H__
#define __DATABASE_HELPER_H__
class DatabaseHelper{
public:
static QJsonDocument* database;
DatabaseHelper();
static Card* selectJSonCard(std::string cardCode);
static void testFunctions();
static bool isLeader(std::string cardCode);
};
#endif
QJsonDocument* DatabaseHelper::database = &(QJsonDocument());
void DatabaseHelper::testFunctions(){
std::cout << "test" << std::endl;
}
//and so on for the others
Now I need it to be included from two different file.
With one is fine, it compiles, but 2 gives me this error:
[ERROR] ./models/../utils/database_helper.h:38:16: error: redefinition of ‘QJsonDocument* DatabaseHelper::database’
38 | QJsonDocument* DatabaseHelper::database = &(QJsonDocument());
| ^~~~~~~~~~~~~~
./utils/database_helper.h:38:16: note: ‘QJsonDocument* DatabaseHelper::database’ previously declared here
38 | QJsonDocument* DatabaseHelper::database = &(QJsonDocument());
| ^~~~~~~~~~~~~~
./models/../utils/database_helper.h:114:6: error: redefinition of ‘static void DatabaseHelper::testFunctions()’
114 | void DatabaseHelper::testFunctions(){
| ^~~~~~~~~~~~~~
./utils/database_helper.h:114:6: note: ‘static void DatabaseHelper::testFunctions()’ previously defined here
114 | void DatabaseHelper::testFunctions(){
| ^~~~~~~~~~~~~~
Where the first file including this is in folder ./models/ and the other one in ./ .
My goal is to be able to access the static function from every file in which I include the header, and have just one istance of the QJsonDocument variable "database". Am I missing something? Is there a way to do it?
>Solution :
QJsonDocument* DatabaseHelper::database = &(QJsonDocument());
This defines DatabaseHelper::database.
Every .cpp file that includes this header file will define this object. An #include directive logically inserts the header file into the including .cpp files. It’s as if every one of your .cpp files, that includes this header file, defines this. That’s how #include works in C++.
Therefore, when two or more .cpp files include this header file, this results in violation of the One Definition Rule, hence your compilation error.
The solution is trivial. Move all definitions into exactly one of your .cpp files.
The same thing applies to void DatabaseHelper::testFunctions(), too.