I'm trying to create a linked list for use on the Arduino, in the Eclipse IDE with the Arduino/Sloeber plugin. The linked list is written in a .h
and .cpp
file, and included locally in the project.
However, when building, I get the error undefined reference to Structures::LinkedList<int>::LinkedList()
.
And despite the fact that I've added the local folder to the list of includes (and it can find the top level file containing setup()
and loop()
), the problem persists;
My relevant file listings are below. Any ideas of what settings I can add to Eclipse in order to solve this? Potentially, could it be something to do with the use of template<typename T>
in the header file?
Thanks very much,
David
FYI: This problem does not occur with the core libraries i.e. I can run examples like Serial and Blink.
My top level .cpp
is pretty simple:
#include "LinkedList.h"
#include "RAStarSearch.h"
#include "Arduino.h"
using namespace Structures;
void setup() { }
void loop() {
LinkedList<int> list = LinkedList<int>();
return;
}
And the referenced .h
is:
#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
#include "Arduino.h"
namespace Structures {
template<typename T>
class LinkedList {
public:
/// Struct inside the class LinkedList
struct Link {
T value;
Link *next;
};
LinkedList<T>(); ///< Default constructor
void addValue(T val); ///< prepends new value at beginning of list
T popValue(); ///< returns first element and deletes Link.
Link* peekLink(); ///< Looks at first value
private:
Link *head; // this is the private member variable. It is just a pointer to the first Node
};
const int ERRNUM = 0x8000000; ///<Error number used, as exceptions not supported
}
#endif /* LINKEDLIST_H_ */
EDIT
On request I have included my code for LinkedList.cpp
#include "LinkedList.h"
#include "Arduino.h"
namespace Structures {
template<typename T>
LinkedList<T>::LinkedList() {
head = NULL; // set head to NULL
}
template<typename T>
void LinkedList<T>::addValue(T val) {
Link *n = new Link(); // create new Node
n->value = val; // set value]
if (head == NULL) { //i.e. if list is empty
n->next = head; // make the node point to the next node or NULL
head = n; // last but not least, make the head point at the new node.
} else {
Link *it = head;
Link *oldIt = NULL;
//TODO check edge cases i.e. insertion at beginning and end of list
while (n->value > it->value){ //until place in list is found, needs T to have > operator
oldIt = it;
it = it->next;
}
oldIt->next = n; //Set pointer to n
n->next = it; //Set n pointer to next
}
}
template<typename T>
T LinkedList<T>::popValue() {
T retval = ERRNUM;
if (head != NULL) {
Link *n = head;
retval = head->value;
head = head->next;
delete n;
}
return retval;
}
template<typename T>
typename LinkedList<T>::Link* LinkedList<T>::peekLink() {
return head;
}
}