Class static variables and functions

I want to move class variables to static as they are common to all instances of the class. I keep getting an “undefined reference” error when I compile. I made up the following test. The variable _species is shared by all class members. This is the main sketch:

//  static class variable and function test

#include <SoftwareSerial.h>

#include "MFF.h"

int sp = 3;
MFF fly = MFF(sp);

void setup() {
  // put your setup code here, to run once:

void loop() {


This is the header file MFF.h.

//  MFF header
#ifndef GUARD_MFF
#define GUARD_MFF

#if (ARDUINO > 100)
#include "Arduino.h"
#include "WProgram.h"

class MFF {
    static int _species;
    int mff_var;
    MFF(const int var);

  //  setters
    static void MFF::set_species(const int species);

  //  getters
    static int MFF::get_species();


And this is the implementation file MFF.cpp.

#include "MFF.h"

MFF::MFF(const int var) {
  mff_var = var;

//  setter
void MFF::set_species(const int species) { _species = species; }

//  getter
int MFF::get_species() { return _species; }

The error messages is as follows:

Arduino: 1.8.12 (Mac OS X), Board: "Arduino/Genuino Uno"

/var/folders/bx/71cpj8fw8xl046001s79p93h0000gp/T//ccahHDyc.ltrans0.ltrans.o: In function `set_species':
sketch/MFF.cpp:8: undefined reference to `MFF::_species'
sketch/MFF.cpp:8: undefined reference to `MFF::_species'
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Uno.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I don’t understand why the public set_species() function can’t be found.

I don’t understand why the public set_species() function can’t be found.

I don’t understand why you think that.

The problem is with the static member variable.

You haven't defined (i.e. allocated storage space for) the static variable. Add to the .cpp file:

int MFF::_species;

gfvalvo: Thanks! That solved the problem. Much appreciated.