未定义的参考C ,不寻常的情况

Undefined reference c++, unusual case

本文关键字:不寻常 情况 参考 未定义      更新时间:2023-10-16

我正在在C 中创建一个队列类,并且在用makefile编译时遇到困难。我的queue.cpp课程在这里

#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"时,我会收到此错误:

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机器。有人会解释吗?

您的makefile不正确 - 它以对queue.o的依赖编译tester.cpp,但根本不会链接queue.o。这就是为什么tester.cpp汇编会导致未解决的参考。

您应该按以下方式更改制作文件:

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