微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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)

这是头文件

#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

这是.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;
}

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

解决方法:

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

尝试添加

int Counter::nCounters = 0;

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

static int nCounters = 0;

代替.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐