0

I've been writing C++ (Mostly C++98) for a while and whenever I have a class using a static variable that is being accessed by a static function I must (re?)define it.

Example:

Test.h

class Test
{
    static bool m_Foo;

    static void Bar();
}

Test.cpp

bool Test::m_Foo; // This is what im trying to get rid of

void Test::Bar()
{
    m_Foo != m_Foo;
}

Now with bigger classes this becomes really messy and confusing, is there a better way to handle this? Im thinking that C11 or C17 would have a more modern way to do this. My google research only really shows solutions for functions.

Sid S
  • 6,037
  • 2
  • 18
  • 24
Flowx
  • 55
  • 1
  • 8
  • 2
    What you are looking for is `inlined variable` (since c++17). See https://en.cppreference.com/w/cpp/language/inline for more details. – ph3rin Aug 20 '19 at 00:28
  • Possible duplicate of [Why static data members must be defined in C++?](https://stackoverflow.com/questions/57387460/why-static-data-members-must-be-defined-in-c) – Justin Aug 20 '19 at 01:12
  • If you have so many statics that this becomes messy and confusing, it might be time to refactor. – molbdnilo Aug 20 '19 at 01:42

2 Answers2

1

static bool m_Foo; in Class Test, is a declaration while bool Test::m_Foo; is its definition, so you can't skip this.

How do I improve it? I'm not quite sure what is the better way to handle it and look forward to see other answers.

Axois
  • 1,961
  • 2
  • 11
  • 22
wei
  • 11
  • 1
0

Using VS2017 you have to explicitly state to use C++17 on all builds. Rookie mistake I know ...
After switching to C++17 (Not C++14) using inline worked straight away.

The Class now looks like this:

class Test
{
    static inline bool m_Foo;

    static void Bar();
}
Flowx
  • 55
  • 1
  • 8