2012-09-03 68 views
-1

我有簡單的類INA頭文件:編譯錯誤未定義的符號

> cat Algorithms.hh 
#ifndef Algorithms_hh 
#define Algorithms_hh 
#include<vector> 
class Algorithms 
{ 
public: 

Algorithms(); 
void BubbleSort(); 

std::vector<int> myarray; 

}; 
#endif 

然後一個相應的C文件:

> cat Algorithms.cc 
#include <iostream> 
#include <vector> 
#include "Algorithms.hh" 

Algorithms::Algorithms() 
{ 
myarray.push_back(0); 
} 


void Algorithms::BubbleSort() 
{ 
     int i, j, flag = 1; // set flag to 1 to start first pass 
     int temp;    // holding variable 
     int numLength = myarray.size(); 
     for(i = 1; (i <= numLength) && flag; i++) 
    { 
      flag = 0; 
      for (j=0; j < (numLength -1); j++) 
     { 
       if (myarray[j+1] > myarray[j])  // ascending order simply changes to < 
       { 
        temp = myarray[j];    // swap elements 
        myarray[j] = myarray[j+1]; 
        myarray[j+1] = temp; 
        flag = 1;    // indicates that a swap occurred. 
       } 
      } 
    } 
} 
> 

然後主要功能:

> cat algo2.cc 
#include <iostream> 
#include <vector> 
#include "Algorithms.hh" 

using namespace std; 

int main(int argc,char **argv) 
{ 

Algorithms *arr=new Algorithms(); 
arr->myarray.push_back(1); 
arr->myarray.push_back(2); 
arr->myarray.push_back(100); 
return 0; 
} 

> 

當我編譯主: 我得到下面的錯誤:

> CC algo2.cc 
Undefined      first referenced 
symbol        in file 
Algorithms::Algorithms()    algo2.o 
ld: fatal: Symbol referencing errors. No output written to a.out 

誰能告訴我我哪裏錯了?

+3

我認爲我們只是* *同意[在其他問題](http://stackoverflow.com/questions/12243621/declaring-a-vector-as-a-class-member)你必須聲明構造函數爲'算法();'而不是'算法: :算法();'?不管別人怎麼看待你對他們的建議和建議,都是一種糟糕的動機。 –

+0

外循環的終止條件是錯誤的:'for(i = 1;(i <= numLength)&& flag; i ++)'。應該是'我

回答

1

這是一個鏈接器錯誤,鏈接器告訴你它無法找到類Algorithms的構造函數的定義。你應該編譯:

CC Algorithms.cc algo2.cc 

您可以識別這是因爲在錯誤面前ld:的連接錯誤。

,當然還有由Kerrek SB說你需要聲明你的構造函數沒有在它前面的Algorithms:: ...

0

你剛纔忘了這兩個.cc的文件包括到編譯:

cc algo2.cc Algorithms.cc 

如果包括關於聲明的頭文件,像

#include "Algorithms.hh" 

您還應該執行,以.c或.LIB定義。或者動態定義加載庫。在你的情況你的庫是Algorithms.cc,所以只需將其添加到編譯階段,然後這兩個臨時對象文件

Algo2.a + Algorithms.a 

會去

a.out