c++ - undefined reference c++,异常情况

标签 c++ linux compilation compiler-errors g++

我正在用 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);
}

生成文件

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”时,出现此错误:

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 不正确 - 它编译 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

关于c++ - undefined reference c++,异常情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13061617/

相关文章:

c++ - AVX2:有没有办法实现 _mm256_mul_epi8 函数的 2 的恒定幂?

c++ - lambda 中的这个 size_t 是做什么的? C++代码

c++ - 如何在 Visual Studio 2010 for Linux 中编译

linux - 将 Meteor MongoDB 从一个 VPS 迁移到另一个?

linux - 修改二进制打包应用的名称及其调用命令

c++ - 我无法从 flandmark v0.7 Plataform x86 Win 7 生成 dll

linux - 根据另一个文件中的字符串拆分一个文件

linux - 如何在 Jenkins 中设置管道构建的字符串名称

java - 类路径中存在大量 jar/class 是否会严重影响编译性能?

c - 查找我需要包含哪些库文件以实现特定的 c 头文件