I'm trying to build a project with the folder structure using Cmake. I'm not sure whether it is a problem with CMake or any other specifics related to the code that I'm missing out. I have implemented all the functions that I have defined and have written a CMake script as explained in the link and still get the following error. can anyone please help?
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
The class declaration is the following code,
#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
The class definition is the following code,
#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++;
}
Thanks.