未定义的函数引用| collect2:错误:ld返回1退出状态

时间:2018-02-16 19:18:12

标签: c++

我尝试使用Cmake使用folder structure构建项目。 我不确定这是否与CMake或我错过的代码相关的任何其他细节有问题。我已经实现了我已定义的所有函数,并编写了一个CMake脚本,如link中所述,仍然会出现以下错误。有人可以帮忙吗?

CMakeFiles/book.dir/main.cpp.o: In function `main':
main.cpp:(.text+0x11): undefined reference to 
`LinkedList<int>::LinkedList()'
main.cpp:(.text+0x2b): undefined reference to 
`LinkedList<int>::insert(int const&)'
main.cpp:(.text+0x45): undefined reference to 
`LinkedList<int>::insert(int const&)'
main.cpp:(.text+0x5f): undefined reference to 
`LinkedList<int>::append(int const&)'
main.cpp:(.text+0x6b): undefined reference to 
`LinkedList<int>::print() const'
main.cpp:(.text+0x7c): undefined reference to 
`LinkedList<int>::~LinkedList()'
main.cpp:(.text+0x8f): undefined reference to 
`LinkedList<int>::~LinkedList()'
collect2: error: ld returned 1 exit status
make[2]: *** [book] Error 1
make[1]: *** [CMakeFiles/book.dir/all] Error 2
make: *** [all] Error 2   

类声明是以下代码,

#ifndef BOOK_LINKEDLIST_H
#define BOOK_LINKEDLIST_H

template <typename E>
class Link {
public:
E element;
Link *next;
Link(const E &ele, Link *n= nullptr) {
    element = ele;
    next = n;
}
Link(Link *n = nullptr) {
    next = n;
}
};
template <typename E>
class LinkedList {
private:
Link<E> *head;
Link<E> *tail;
Link<E> *curr;
int count;

void init();

void removeAll();

public:
LinkedList();
~LinkedList();

void print() const ;
void clear();

void insert(const E &item);
void append(const E &item);
};

#endif //BOOK_LINKEDLIST_H

类定义是以下代码,

#include "LinkedList.h"
#include "cstdio"

template<typename E>
void LinkedList<E>::removeAll() {
while (head != nullptr) {
    curr = head;
    head = head->next;
    delete curr;
}
}

template<typename E>
void LinkedList<E>::init() {
head = tail = curr = new Link<E>;
count = 0;
} 

template<typename E>
LinkedList<E>::LinkedList() { init(); }

template<typename E>
LinkedList<E>::~LinkedList() {removeAll();}

template<typename E>
void LinkedList<E>::print() const {
printf("List: \n");
Link<E> *temp = head;
while(temp != nullptr) {
    printf("%d ", temp->element);
    temp = temp->next;
}
printf("\n");
}

template<typename E>
void LinkedList<E>::clear() {removeAll(); init();}

template<typename E>
void LinkedList<E>::insert(const E &item) {
curr->next = new Link<E>(item, curr->next);
if (tail == curr) tail = curr->next;
count++;
}

template<typename E>
void LinkedList<E>::append(const E &item) {
tail = tail->next = new Link<E>(item, nullptr);
count++;
}

感谢。

0 个答案:

没有答案