E.C*_*oss 2 c++ linux compiler-errors compilation 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 ++;
}
Run Code Online (Sandbox Code Playgroud)
我的头文件(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.
};
Run Code Online (Sandbox Code Playgroud)
测试程序(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);
}
Run Code Online (Sandbox Code Playgroud)
生成文件
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
Run Code Online (Sandbox Code Playgroud)
当我输入"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
Run Code Online (Sandbox Code Playgroud)
关于它的不寻常之处在于,当在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
Run Code Online (Sandbox Code Playgroud)