2011-01-08 6 views
0

私はプロジェクトに取り組んでいましたが、ファイルに分割することに決めました。しかし、私はこのような問題に悩まされ、私はGoogle経由で見つけたすべてのアドバイスは、私が正しくやっている両方のオブジェクトファイルをリンクすることを忘れていた(少なくとも私はそう考える)。C++でヘッダーをインクルードしているときの未定義の参照

の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() { 
    cout << this->a << endl; 
} 
}; 

エラーメッセージ:だからここ

[email protected]:~/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 

答えて

4

あなたは間違ってやったことです。 class.cで、新しい Tridaクラスを再作成します。これは、class.hで作成したものを実装するのではなく、

#include <iostream> 
#include "class.h" 

using namespace std; 

Trida::Trida(int n) 
{ 
    this->a = n; 
} 

void Trida::fce() { cout << this->a << endl; } 

を本当にあなたのコンストラクタで代入するのではなく、初期化を使用する必要があります:あなたのclass.cppがより次のようになります。あなたは、ヘッダファイルにクラスtrida 2回(定義されている

Trida::Trida(int n) : a(n) {} 
+0

うわーそれは速かったようにする必要があります。問題は私が思ったよりも簡単です。どうもありがとうございました :-) – Gwynbleidd

0

class.hとソースファイルclass.cpp中) あなたclass.cppファイルが

#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; 
}