2012-10-25 56 views
2

我在C++中創建了一個隊列類,並且遇到了編譯makefile的麻煩。我queue.cpp類是這裏未定義的引用C++,不常見的情況

#include "queue.h" 
#include <stdlib.h> 

queue::queue() 
{ 
    front_p = NULL; 
    back_p = NULL; 
    current_size = 0; 
} 

void queue::enqueue(int item) 
{ 
    node newnode = node(item, NULL); 
    if (front_p == NULL) //queue is empty 
    { 
     front_p = &newnode; 
     back_p = &newnode; 
    } 
    else 
    { 
     back_p->next = &newnode; 
     back_p = &newnode; 
    } 
    current_size ++; 
} 

我的頭文件(queue.h)是這裏

class queue 
{ 
    public: 
    queue(); // constructor - constructs a new empty queue. 
    void enqueue(int item); // enqueues item. 
    int dequeue(); // dequeues the front item. 
    int front(); // returns the front item without dequeuing it. 
    bool empty(); // true iff the queue contains no items. 
    int size(); // the current number of items in the queue. 
    int remove(int item); // removes all occurrances of item 
     // from the queue, returning the number removed. 

    private: 
    class node // node type for the linked list 
    { 
     public: 
      node(int new_data, node * next_node){ 
       data = new_data ; 
       next = next_node ; 
      } 
      int data ; 
      node * next ; 
    }; 

    node* front_p ; 
    node* back_p ; 
    int current_size ; // current number of elements in the queue. 
}; 

測試程序(tester.cpp)

#include <iostream> 
#include "queue.h" 
#include <stdlib.h> 
using namespace std; 

int main(int argc, char * const argv[]) 
{ 
    cout << "Lalalalala" << endl; 
    queue q1; 
    q1.enqueue(5); 
} 

的makefile

all: tester 

tester: queue.o 
    g++ -o tester tester.cpp 

queue.o: queue.cpp queue.h 
    g++ -c queue.cpp 

clean: 
    rm -f tester *.o 

當我輸入「make」或「make all」時,我得到這個e RROR:

g++ -o tester tester.cpp 
/tmp/ccTOKLWU.o: In function `main': 
tester.cpp:(.text+0x33): undefined reference to `queue::queue()' 
tester.cpp:(.text+0x44): undefined reference to `queue::enqueue(int)' 
collect2: ld returned 1 exit status 
make: *** [tester] Error 1 

關於它的不尋常的事情,是在Windows機器上在Visual Studio中進行編譯時,沒有錯誤。我沒有最明顯的想法,爲什麼它不應該像我這樣在Linux機器上編譯。誰會好心解釋?

回答

8

您的生成文件不正確 - 它編譯tester.cpp時依賴於queue.o,但它根本不鏈接queue.o。這就是爲什麼彙編tester.cpp導致未解決的參考。

如下您應該更改make文件:一個........

all: tester 

tester: queue.o tester.o 
    g++ queue.o tester.o -o tester 

tester.o: tester.cpp tester.h 
    g++ -c tester.cpp 

queue.o: queue.cpp queue.h 
    g++ -c queue.cpp 

clean: 
    rm -f tester *.o 
+0

兒子謝謝我的朋友,這是竊聽我!我仍然不完全熟悉makefile的概念。 –