1

What I want to do is simply;

  • Using a static class without instantiating (preferable a Singleton)
  • And setting some static class variables within some static setter/getter.

It look super easy but I couldn't find any example on the internet wired. Whatever I do gives; undefined reference to `Test::_pin' error! I does NOT compile.

My class header Test.h:

#ifndef Test_h
#define Test_h
#include "Arduino.h"

class Test
{
    public:
    Test(byte pin);
    static byte getPin();
    static byte _pin;    

    private:

};
#endif

My class code Test.cpp:

#include "Test.h"

Test::Test (byte pin) {
    _pin = pin;
}

byte Test::getPin(){
    return _pin;
}

StaticClassTest.ino:

#include "Test.h"

void setup()
{
    Test(5);
    Serial.begin(9600);
    Serial.println(Test::getPin(), DEC);
}
void loop() { }

I've already tried to access _pin with:

byte Test::getPin(){
    return Test::_pin;  // did NOT work, reference error
}

Ideally, _pin should be in private: and accessible by my getPin(); But as it is impossible to set/get this variable I put in public to have more chance.

What is wrong in this simple context?

How can I set/get this variable in this class?

Trevor
  • 1,051
  • 12
  • 16

1 Answers1

4

In Test.cpp add:

byte Test::_pin;

and it'll work.

It's just declaration inside of class, and you have to make a space for this variable too (by adding definition).

More info in similar Q&A on SO and all possibilities on cppreference.com

Community
  • 1
  • 1
KIIV
  • 3,534
  • 2
  • 18
  • 23
  • Thank you @KIIV with this second definition in Test.cpp it worked! I'm still surprised and confused. Why we need this second memory allocation? I spent around 6 hours because of this exception :-/ again, thank you! Cheers, – Trevor Sep 05 '16 at 23:58