Undefined reference while including header in C++
I was working on my project while I decided that I should split it into files. However I got stucked with problem like this and all advice I found via google were about forgetting to link both object files which I am doing right (at least I think so).
Makefile:
test : class.o main.o
g++ class.o main.o -o test.exe
main.o : main.cpp
g++ main.cpp -c
class.o : class.cpp
g++ class.cpp -c
main.cpp
#include <iostream>
#include "class.h"
using namespace std;
int main() {
Trida * t = new Trida(4);
t->fce();
return 0;
}
class.h
#ifndef CLASS
#define CLASS
class Trida {
private:
int a;
public:
Trida(int n);
void fce();
};
#endif
class.cpp
#include <iostream>
using namespace std;
class Trida {
private:
int a;
public:
Trida(int n) {
this->a = n;
}
void fce() {
co开发者_运维问答ut << this->a << endl;
}
};
Error message:
gwynbleidd@gwynbleidd-pc:~/Skola/test$ make
g++ class.cpp -c
g++ main.cpp -c
g++ class.o main.o -o test.exe
main.o: In function `main':
main.cpp:(.text+0x26): undefined reference to `Trida::Trida(int)'
main.cpp:(.text+0x54): undefined reference to `Trida::fce()'
collect2: ld returned 1 exit status
make: *** [test] Error 1
So here's what you did wrong. In class.cpp you recreate a new Trida class rather than implement the one you've created in class.h. Your class.cpp should look more like this:
#include <iostream>
#include "class.h"
using namespace std;
Trida::Trida(int n)
{
this->a = n;
}
void Trida::fce() { cout << this->a << endl; }
And really you should be using initialization rather than assignment in your constructor:
Trida::Trida(int n) : a(n) {}
You are defining class trida
two times (in the header file class.h
and in the source file class.cpp
)
Your class.cpp file should be like
#include <iostream>
#include "class.h" //include "class.h"
using namespace std;
Trida::Trida(int n):a(n) //Initialization list
{
}
void Trida::fce()
{
cout << this->a << endl;
}
精彩评论