4

I'm having difficulty getting this to compile. I think the it has to do with the static variables, but I'm not 100% sure what I'm doing. Here is the error message I keep getting:

Undefined symbols for architecture x86_64: "Counter::nCounters", referenced from: Counter::Counter(int, int) in main.o

Counter::getNCounters() in main.o

Counter::Counter(int, int) in Counter.o

Counter::getNCounters() in Counter.o

ld: symbol(s) not found for architecture x86_64

clang: error: linker command failed with exit code 1 (use -v to see invocation)

Here is the header file:

#ifndef project1_Counter_h
#define project1_Counter_h

class Counter
{
private:
int counter;
int limit;
static int nCounters;

public:
Counter(int, int);
void increment();
void decrement();
int getValue();
static int getNCounters();
};

#endif

And here is the .cpp file:

#include "Counter.h"

Counter::Counter(int a, int b)
{
counter = a;
limit = b;
nCounters++;
}

void Counter::increment()
{
if (counter < limit)
    counter++;
}

void Counter::decrement()
{
if (counter > 0)
    counter--;
}

int Counter::getValue()
{
return counter;
}

int Counter::getNCounters()
{    
return nCounters;
}

And the main.cpp is just a simple Hello World program. Any help would be appreciated.

Coding Mash
  • 3,338
  • 5
  • 24
  • 45
MadDash
  • 43
  • 1
  • 3

1 Answers1

7

I believe you need to initialize nCounters with a value.

Try adding

int Counter::nCounters = 0;

somewhere outside the class, or initialize it as:

static int nCounters = 0;

instead.

Serge
  • 1,974
  • 6
  • 21
  • 33
  • 1
    ya, every Static variable should be initialized in the .cpp file. Its better to put all the static variable initializations in the top of your .cpp with a bit comment like `/* -- Static Variables -- */` for the readability. – Deamonpog Oct 19 '12 at 05:34
  • 2
    Thanks, but I still have the clang: error: linker command failed with exit code 1 (use -v to see invocation) – MadDash Oct 19 '12 at 05:37