0

Returning or accessing a static variable inside a static function throws an error in Visual Studio:

// H File
class LayoutManager : public QObject
{
    static int Access_Data();
    static int data;
};
// CPP

static int data= 0; // Global scope

int LayoutManager::Access_Data()
{
    data= data+ 1;
    return data;
}
Error: Error    LNK2001 unresolved external symbol "public: static int LayoutManager::data" (?mm@LayoutManager@@2HA)

After changing to int LayoutManager::data = 0 in C++, the error is gone, but while assigning a new value to data in another class, it throws a new error:

void MyLayout::Update( void )
{
    LayoutManager::data = 1;  // error here
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Sijith
  • 3,740
  • 17
  • 61
  • 101
  • Please don't edit answers into your question, if the answer didn't solve your problem add a comment to the answer. If you have a new question raise a new question – Alan Birtles Nov 04 '20 at 07:37

1 Answers1

1

Try this

int LayoutManager::data = 0;

This tells the compiler that you mean the data variable in the LayoutManager class and not a regular global variable outside of any class.

It's also an error to repeat the static keyword. The compiler already knows the variable is static from the declaration.

john
  • 85,011
  • 4
  • 57
  • 81