Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static const in classes

Tags:

c++

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.

like image 497
MarcoS Avatar asked Mar 12 '26 23:03

MarcoS


1 Answers

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.

like image 125
Alok Save Avatar answered Mar 14 '26 12:03

Alok Save



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!