I have made the following C++ program which is made up of 3 files:
The thing.h file
#ifndef THING_H
#define THING_H
class thing{
double something;
public:
thing(double);
~thing();
double getthing();
void setthing(double);
void print();
};
#endif
The thing.cpp file
#include <iostream>
#include "thing.h"
thing::thing(double d){
something=d;
}
thing::~thing(){
std::cout << "Destructed" << std::endl;
}
double thing::getthing(){
return something;
}
void thing::setthing(double d){
something = d;
}
void thing::print(){
std::cout <<"The someting is " << something << std::endl;
}
The main file
#include <iostream>
#include "thing.h"
int main(){
thing t1(5.5);
t1.print();
t1.setthing(7.);
double d=t1.getthing();
std::cout << d << std::endl;
system("pause");
return 0;
}
I had made this program previously all in one file and it ran perfectly but when I try split it into seperate files to create a header I get a linker error, here is the errors I get when I try run it from the main file:
[Linker error] undefined reference to `thing::thing(double)'
[Linker error] undefined reference to `thing::print()'
[Linker error] undefined reference to `thing::setthing(double)'
[Linker error] undefined reference to `thing::getthing()'
[Linker error] undefined reference to `thing::~thing()'
[Linker error] undefined reference to `thing::~thing()'
ld returned 1 exit status
From the above errors it seems asthough the main file doesnt recognise the functions inside the header, how do I fix this please?
In slightly less pedantic terms:
Your header file
thing.hdeclares “whatclass thingshould look like”, but not its implementation, which is in the source filething.cpp. By including the header in your main file (we’ll call itmain.cpp), the compiler is informed of the description ofclass thingwhen compiling the file, but not howclass thingactually works. When the linker tries to create the entire program, it then complains that the implementation (thing::print()and friends) cannot be found.The solution is to link all the files together when creating the actual program binary. When using the g++ frontend, you can do this by specifying all the source files together on the command line. For example:
will create the main program called “main”.