C++;:包含头文件编译失败,但包含源cpp文件编译失败 这可能很简单,但它阻碍了我在C++道路上的前进。 我现在正在阅读加速C++,我决定把一个练习题翻过头。这一切都运行良好,我的代码运行良好,直到我将其拆分为一个头文件和单独的源文件。当我导入包含我编写的一些函数的.cpp源文件时,一切运行正常。但是当我试图通过头文件导入函数时,它失败得很厉害,我得到了以下错误。 我是用Geany的gcc编译的,到目前为止一切都很好。谢谢你的帮助

C++;:包含头文件编译失败,但包含源cpp文件编译失败 这可能很简单,但它阻碍了我在C++道路上的前进。 我现在正在阅读加速C++,我决定把一个练习题翻过头。这一切都运行良好,我的代码运行良好,直到我将其拆分为一个头文件和单独的源文件。当我导入包含我编写的一些函数的.cpp源文件时,一切运行正常。但是当我试图通过头文件导入函数时,它失败得很厉害,我得到了以下错误。 我是用Geany的gcc编译的,到目前为止一切都很好。谢谢你的帮助,c++,gcc,header-files,C++,Gcc,Header Files,错误: 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> >

错误:

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
g++-Wall-o“quartile”“quartile.cpp”(在目录:/home/charles/Temp中)
编译失败。
/tmp/ccJrQoI9.o:在函数“main”中:
quartile.cpp:(.text+0xfd):对“quartile(std::vector)”的未定义引用
collect2:ld返回了1个退出状态

“统计数字h”:

\ifndef GUARD\u stats\u h
#定义守卫统计信息
#包括
标准:向量四分位数(标准:向量);
#恩迪夫

“stats.cpp”:

#包括
#包括
#包括“stats.h”
使用std::vector;使用std::sort;
双中位数(向量向量向量){
//代码。。。
}
向量四分位数(向量向量向量){
//代码,我也从这里引用中间值。
}
“四分位数cpp”:

#包括
#包括
#包括“stats.h”//如果我将其更改为“stats.cpp”,它会起作用
使用std::cin;使用std::cout;
使用std::vector;
int main(){
//这里是四分位函数的代码和参考。
}

编译失败,因为您只声明了此函数。它的定义在不同的编译单元中,您不能将这两者链接在一起


执行
g++-Wall-o quartile quartile.cpp stats.cpp
,它就会工作。

您需要告诉g++关于这两个.cpp输入文件的信息。我不是g++方面的专家,但它看起来像是一个链接器错误


g++-Wall-o“quartile”“quartile.cpp”“stats.cpp”

非常感谢您,正如我所说的简单,但您所节省的痛苦是难以置信的。我在读这本书的时候很好奇,我不知道stats.h会如何找到stats.cpp,只是相信它会使用一些魔法,就像python的导入一样。
#ifndef GUARD_stats_h
#define GUARD_stats_h

#include <vector>

std::vector<double> quartile(std::vector<double>);

#endif
#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.
}
#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.
}