C ++:包括头文件编译失败,但包括源cpp文件编译 [英] C++: Including header-file fails compilation but including source cpp file compiles
问题描述
这可能是很简单,但它阻碍了我在我的路上c ++路。
我目前正在通过加速c ++阅读,我决定过度练习一个练习。这一切都很好,我的代码运行良好,直到我把它拆分成一个头和单独的源文件。当我导入我的.cpp源文件包含一些我写的函数,一切运行正常。但是当我尝试通过头文件导入函数它失败可怕,我得到以下错误。
我正在从Gany编译gcc,它都工作正常,直到现在。感谢任何帮助。
This is probably really simple, but it's hindering me on my way down c++ road. I am currently reading through accelerated c++ and I decided to overkill one of the exercises. It all worked well and my code ran fine until I split it into a header and separate source file. When I import my .cpp source file containing some functions I wrote, everything runs fine. But when I try to import the functions through a header file it fails horribly and I get the following error. I am compiling with gcc from Geany, it's all worked fine until now. Thanks for any help.
错误:
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:
"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.
}
推荐答案
编译失败,只声明这个函数。
Compilation fails, because you have only declared this function. Its definition is in different compilation unit, and you're not linking those two together.
做 g ++ -Wall -o quartile quartile.cpp stats .cpp
,它会工作。
这篇关于C ++:包括头文件编译失败,但包括源cpp文件编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!