Static functions and variables

I know what I am trying to achieve, but really struggling to figure out how to achieve that. To illustrate this, I have made a simple project that consists of one .ino file, call it Sketch.ino; one header file, call it Module.h; and its associated .cpp file - call it Module.cpp. Here’s the ino file:-

#include "Module.h"
void setup() {
  MyClass::Initialise();
}
void loop()  { }

Here’s the header:-


class MyClass{
  public:
    static void Initialise();
    static bool m_bVariable;
};

And here’s the code:-

#include <Arduino.h>
#include "Module.h"

void MyClass::Initialise() {
  m_bVariable = true;
}

Essentially, I want to have a class (as opposed to instance) level variable; so the same quantity is shared for every instance of the class. I then want to provide a class level function to operate on that variable. So, I have made both the variable and the function static.

When I compile this under IDE 2.3.8 for a basic Arduino nano, the following error results:-

C:\Users\rtdgr\AppData\Local\Temp\ccWjxLsu.ltrans0.ltrans.o: In function `Initialise':
C:\Users\rtdgr\OneDrive\Documents\Arduino\Sketch/Module.cpp:5: undefined reference to `MyClass::m_bVariable'
collect2.exe: error: ld returned 1 exit status
exit status 1

Compilation error: exit status 1

I’m afraid I haven’t figured out how I need to change this to get it to compile. I also fancy there’s somebody reading this forum who immediately knows exactly what I’ve done wrong. Any recommendations?

You started a topic in the Uncategorised category of the forum when its description explicitly tells you not to

Your topic has been moved to a relevant category. Please be careful in future when deciding where to start new topics

#include <Arduino.h>
#include "Module.h"

bool MyClass::m_bVariable;

void MyClass::Initialise() {
  MyClass::m_bVariable = true;
}

Your .h file only has the declaration. You left out the definition.

That’s precisely it. I wasn’t seeing it. Many thanks.

That just happened to happen to me, and I was wrong to think that

class MyClass{
  public:
    static void Initialise();
    static bool m_bVariable;
};

defined m_bVariable.

Look forward (?) to C++17+, where you can just write

class MyClass{
  public:
    static void Initialise();
    inline static bool m_bVariable;
};

a7