C++编译错误:体系结构x86_64的未定义符号

Mad*_*ash 3 c++ 64-bit xcode build

我很难将其编译.我认为它与静态变量有关,但我不是100%肯定我在做什么.以下是我不断收到的错误消息:

体系结构x86_64的未定义符号:"Counter :: nCounters",引自:main.o中的Counter :: Counter(int,int)

main.o中的Counter :: getNCounters()

Counter.o中的Counter :: Counter(int,int)

Counter.o中的Counter :: getNCounters()

ld:找不到架构x86_64的符号

clang:错误:链接器命令失败,退出代码为1(使用-v查看调用)

这是头文件:

#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
Run Code Online (Sandbox Code Playgroud)

这是.cpp文件:

#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;
}
Run Code Online (Sandbox Code Playgroud)

而main.cpp只是一个简单的Hello World程序.任何帮助,将不胜感激.

Ser*_*rge 6

我相信你需要用一个值来初始化nCounters.

尝试添加

int Counter::nCounters = 0;
Run Code Online (Sandbox Code Playgroud)

在课外的某个地方,或将其初始化为:

static int nCounters = 0;
Run Code Online (Sandbox Code Playgroud)

代替.

  • 谢谢,但我仍然有 clang: error: linker command failed with exit code 1 (使用 -v 查看调用) (2认同)