这可能很简单,但它在我走下c ++路的过程中阻碍了我。 我目前正在通过加速c ++阅读,我决定过度使用其中一个练习。这一切都运行良好,我的代码运行良好,直到我将它分成一个标题和单独的源文件。当我导入包含我写的一些函数的.cpp源文件时,一切运行正常。但是,当我尝试通过头文件导入函数时,它失败可怕,我得到以下错误。 我正在使用Geany的gcc进行编译,直到现在它都运行良好。谢谢你的帮助。
错误:
g++ -Wall -o "quartile" "quartile.cpp" (in directory: /home/charles/Temp)
Compilation failed.
/tmp/ccJrQoI9.o: In function `main':
quartile.cpp:(.text+0xfd): undefined reference to `quartile(std::vector<double, std::allocator<double> >)'
collect2: ld returned 1 exit status
“stats.h”:
#ifndef GUARD_stats_h
#define GUARD_stats_h
#include <vector>
std::vector<double> quartile(std::vector<double>);
#endif
“stats.cpp”:
#include <vector>
#include <algorithm>
#include "stats.h"
using std::vector; using std::sort;
double median(vector<double> vec){
//code...
}
vector<double> quartile(vector<double> vec){
//code and I also reference median from here.
}
“quartile.cpp”:
#include <iostream>
#include <vector>
#include "stats.h" //if I change this to "stats.cpp" it works
using std::cin; using std::cout;
using std::vector;
int main(){
//code and reference to quartile function in here.
}
答案 0 :(得分:7)
编译失败,因为您只声明了此函数。它的定义是在不同的编译单元中,你没有将这两者联系起来。
执行g++ -Wall -o quartile quartile.cpp stats.cpp
并且它会起作用。
答案 1 :(得分:0)
你需要告诉g ++两个.cpp输入文件。我不是g ++的专家,但它看起来像链接器错误。
像
g ++ -Wall -o“quartile”“quartile.cpp”“stats.cpp”