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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.