Tuesday, 6 September 2016

c++ - Why am I getting this undefined symbols for architecture x86_64 error





I am getting an Undefined symbols for architecture x86_64 error but I'm not sure why.
I am making a stack data type using linked lists and templates.



StackLinkedList.h




#ifndef __StackLinkedList__StackLinkedList__
#define __StackLinkedList__StackLinkedList__

#include
using namespace std;

#endif /* defined(__StackLinkedList__StackLinkedList__) */

template
class StackLinkedList {

public:
StackLinkedList();
void push(Item p);

private:

StackLinkedList* node;
Item data;
};



StackLinkedList.cpp



#include "StackLinkedList.h"

template

StackLinkedList::StackLinkedList() {
node = NULL;
}

template


void StackLinkedList::push(Item p) {
if(node == NULL) {

StackLinkedList* nextNode;
nextNode->data = p;
node = nextNode;
}else {
node->push(p);
}
}



main.cpp



#include "StackLinkedList.h"

int main() {
StackLinkedList* stack;

stack->push(2);
}



Error details:



Undefined symbols for architecture x86_64:
"StackLinkedList::push(int)", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)



I am using Xcode 6.1.


Answer



You have to declare/define your template function in the header file, as the compiler must use the information at compile time about the instantiation type. So put the definitions of the template functions inside the .h file, and not in the cpp.



See
Why can templates only be implemented in the header file?
for more details.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...