简体   繁体   中英

C++ Compiling error: Undefined symbols for architecture x86_64

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM