Error: undefined reference to a static variable

I'm getting an error of undefined reference to a static variable. Let see an example code:

/*
test_static.ino:
--------------------------------
*/

class A
{
private:
   int a;
   static int b;
public:
   A(int i, int j) // Constructor
   {
       a=i;
       b=j;
   }
   void fun1()
   {
       a++; // Acceptable
       b++; // Acceptable
   }
   static void fun2()
   {
       b++; // Acceptable
   }
};

A obj(1,2);

void setup() {
}

void loop() {
}

In the previous code I need that fun2() be static so the variable 'b' should also be static, but I get the following compiler error:

C:\Users\ADMINI~1\AppData\Local\Temp\ccKAsoZy.ltrans0.ltrans.o: In function `_GLOBAL__sub_I_obj':
E:\_arduino\test_static/test_static.ino:15: undefined reference to `A::b'
E:\_arduino\test_static/test_static.ino:15: undefined reference to `A::b'
collect2.exe: error: ld returned 1 exit status

If I remove static from the variable 'b' then the error changes to:

E:\_arduino\test_static\test_static.ino: In static member function 'static void A::fun2()':
test_static:10: error: invalid use of member 'A::b' in static member function
    int b;
        ^
test_static:24: error: from this location
        b++; // Acceptable
        ^
exit status 1

This is expected as fun2() is a static function and can only use static variables or functions.

If I remove static from fun2() then the code compiles without errors.

Any idea why I cannot use fun2() and 'b' as static ?

Because you have not yet allocated storage space for the static variable:

class A {
  private:
    int a;
    static int b;
  public:
    A(int i, int j)   {
      a = i;
      b = j;
    }
    void fun1()   {
      a++; // Acceptable
      b++; // Acceptable
    }
    static void fun2()   {
      b++; // Acceptable
    }
};

int A::b;  // <-------- ALLOCATE MEMORY FOR THE STATIC VARIABLE ---------------

A obj(1, 2);

void setup() {
}

void loop() {
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.