C++: Including header-file fails compilation but including source cpp file compiles

こ雲淡風輕ζ 提交于 2019-12-11 15:17:12

问题


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.

error:

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

回答1:


Compilation fails, because you have only declared this function. Its definition is in different compilation unit, and you're not linking those two together.

Do g++ -Wall -o quartile quartile.cpp stats.cpp and it'll work.




回答2:


You need to tell g++ about both .cpp input files. I'm not expert in g++, but it looks like a linker error.

Like

g++ -Wall -o "quartile" "quartile.cpp" "stats.cpp"



来源:https://stackoverflow.com/questions/1483491/c-including-header-file-fails-compilation-but-including-source-cpp-file-compi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!