Search code examples
c++staticclass-members

static class member gets "undefined reference". Don't know why


I don't know what is wrong with this code. I have the following, very simple, class:

class SetOfCuts{
public:

  static LeptonCuts   Leptons;
  static ElectronCuts TightElectrons;
  static ElectronCuts LooseElectrons;
  //***
  //more code
};

and, for example, the type ElectronCuts is defined before in the same .h file as:

struct ElectronCuts{
  bool Examine;
  //****
  //other irrelevant stuff
};

Nothing too complicated, I think.

My understanding is that, in the main program, I can do:

SetOfCuts::LooseElectrons.Examine = true;

but if I do this, I get:

 undefined reference to `SetOfCuts::LooseElectrons'

If, instead, I do:

 bool SetOfCuts::LooseElectrons.Examine = true;

I get:

error: expected initializer before '.' token

I don't know why I cannot access the members of the structs. I am missing something obvious about static data members but I don't know what it is.

Thanks a lot.


Solution

  • Any static reference must be declared also in a specific source file (and not only in the header file) since it must exists somewhere when linking is done.

    For example if you have this in your Foo.h

    class SetOfCuts{
    public:
    
      static LeptonCuts   Leptons;
      static ElectronCuts TightElectrons;
      static ElectronCuts LooseElectrons;
    };
    

    Then in Foo.cpp you will have

    #include <Foo.h>
    LeptonCuts SetOfCuts::Leptons = whatever;
    ElectronCuts SetOfCuts::ThighElectrons = whatever;
    ..
    

    Finally in your main.cpp you will be able to do

    #include <Foo.h>
    SetOfCuts::Leptons = whatever;