views:

385

answers:

2

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.
}
+6  A: 

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.

PiotrLegnica
Thank you very much, as I said simple but the amount of pain you have saved is incredible. I wondered about that when reading the book, I had no idea how stats.h would find stats.cpp, just believed it would use some magic, much like python's import.
Chazadanga
A: 

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"

queen3