【发布时间】:2013-07-10 11:38:27
【问题描述】:
我正在学习 C++ 的一些基本概念,但我一直在使用标头来使用多个文件。 我有 3 个文件。
计算器.h
#ifndef CALCULATOR_H_CAL
#define CALCULATOR_H_CAL
class Calculator{
int a,b;
public:
Calculator();
Calculator(int,int);
int op();
};
#endif
计算器.cpp
#include<iostream>
#include "Calculator.h"
Calculator::Calculator(){
a=0;b=0;
}
Calculator::Calculator(int c,int d){
a=c;b=d;
}
int Calculator::op(){
return a*b;
}
Main.cpp
#include<iostream>
#include "Calculator.h"
int main(){
Calculator a(2,3);
int b=a.op();
std::cout << b;
}
但是用 g++ Main.cpp 编译会报错:
/tmp/cc09isjx.o: In function `main':
Main.cpp:(.text+0x83): undefined reference to `Calculator::Calculator(int, int)'
Main.cpp:(.text+0x8c): undefined reference to `Calculator::op()'
collect2: ld returned 1 exit status
这里有什么问题?
【问题讨论】:
-
因为他找不到方法的实现。试试 g++ Main.cpp Calculator.cpp
-
标题包含是一个编译问题,你没有问题。未定义的引用是一个链接问题,与标题完全无关。
-
哦。我不知道,您需要指定所有文件名。谢谢。
-
你需要指定链接部分的文件
-
既然你刚刚开始学习 C++,那么现在你应该学习的一些东西是“编译单元”和“链接”的概念。关于这件事有大量的文档,所以我会让你研究一下。
标签: c++ compiler-errors g++