0

I have an enum as a class member in MyClass:

.h file:

private:
enum pattern { PAT_ZERO, PAT_SEQ, PAT_PIPE };
static enum pattern pattern;

I use it in a function:

.cpp file:

int MyClass::function(){
    switch (pattern) {
       case PAT_ZERO:
         break;

It compiles, but I get a linker error.

 In function `MyClass::function()':
MyClass.cpp:(.text._ZN12MyClass11functionEP6threadPvj+0x120): undefined reference to `MyClass::pattern'

I can't seem to figure out why it's an "undefined reference".

tzippy
  • 6,458
  • 30
  • 82
  • 151
  • 1
    Static class member variables are only *declared* in the class, they have to be *defined* as well. There are thousands of duplicates here on SO, do some searching. – Some programmer dude Jan 28 '14 at 09:22

1 Answers1

3

Static data members usually need a definition, as well as the declaration in the class, so add one to the source file:

enum MyClass::pattern MyClass::pattern = PAT_ZERO;

The initialiser is optional - it will be zero-initialised (i.e. initialised to PAT_ZERO) if you leave it out.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644