2017-03-19 51 views
-2

當我編譯此代碼時,我有2個錯誤「未定義的引用test :: setTest(int)」和「未定義的引用test :: getTest()」。我不知道發生了什麼錯誤,我用G ++編譯器在Arch Linux的:未定義對`test :: setTest(int)'的引用

test.h

class test{ 
    int i; 
    public : 
    void setTest(int); 
    int getTest(); 

    }; 

TEST.CPP

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

    void test :: setTest(int x){ 
      i = x; 
} 
    int test :: getTest(){ 
     return i; 
} 

mainTest.cpp

#include<iostream> 
#include"test.h" 
using namespace std; 
int main(){ 
    test t; 
    t.setTest(5); 
    cout<< "the value of i is : "<<t.getTest(); 

} 
+1

你如何建立?你用* *源文件(或目標文件)構建? –

+0

首先我構建mainTest.cpp並獲取2錯誤,然後構建test.cpp,但再次出錯 – AmirHosein

+0

您是否嘗試過*在構建時將兩個源文件作爲參數傳遞?互聯網上可能有成千上萬的例子(包括許多這樣的例子),告訴你如何使用多個源文件構建程序,只需使用普通的GCC。 –

回答

1

你並沒有將兩個文件編譯在一起,所以輸出的可執行文件沒有引用類的方法,只是o n您的終端做:

g++ mainTest.cpp test.cpp -o mainTest 

然後運行它爲:

./mainTest