How to avoid multiple definition of memeber variable?

I got a multiple definition error of member variable

In my header file,

class A{
static int val;
}
.
.
int A::val=0;
(I defined member variable and initialized it)

and In my cpp file,

I used it (like val=val+1;, I didn't define it in cpp file)

why this error occurs?

You are only allowed to create ONE instance of static variables in your program.

If you create it in the header, then you are creating it every time you include that header.

Put int A::val=0; in a cpp file.
If you use C++17 another option is to make it an inline variable. Then you don't need to define it anywhere outside the class definition.

1
2
3
class A{
	static inline int val = 0;
};
thanks guys!
I solved the problem!
really appreciate:)

Topic archived. No new replies allowed.