Reputation: 160
I think is an old question but I don't get it.
I have a header routines.h, its functions file routines.cpp and the main file main.cpp.
In the header there is:
class myclass{
public:
static const double a;
void mymethod();
};
const double myclass::a=0.0;
The routines.cpp contains: #include"routines.h"
and then define the methods.
main.cpp also has #include"routines.h"
.
This setup gives a link error: a it's already defined.
public: static double const myclass::a" (?a148@myclass@@2NB) already defined in DBFLOWPAR2.obj
DBFLOWPAR2 is my main file.
If I define the methods in routines.h it works fine, but I don't like that. What else it's possible? I don't care how the variables are defined, I just want to be able to access myclass.a and find the right value in it.
Upvotes: 3
Views: 720
Reputation: 168626
You have violated the One Definition Rule. Because you #include "routines.h"
in multiple files, the definition of myclass::a
appears in multiple files.
You must define a variable once, and only once.
Choose a convenient .cpp
file, and move your definition to that .cpp
.
Upvotes: 3
Reputation: 258608
class myclass{
public:
static const double a;
void mymethod();
};
const double myclass::a;
The way you have it now, you're redefining myclass::a
in every translation unit that includes the header.
Upvotes: 1
Reputation: 96258
Don't put const double myclass::a=0.0;
in the header file, otherwise each compilation unit including this file will have it's own separate variable. put this to routines.cpp.
Upvotes: 0
Reputation: 206526
You should define the static variable in a cpp file.
Move,
const double myclass::a=0.0;
to your cpp
file.
Defining a
in header file creates a copy of the variable in each Translation Unit where the header is included.
Upvotes: 4