1

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 <iostream>
using namespace std;

#endif /* defined(__StackLinkedList__StackLinkedList__) */

template <class Item>
class StackLinkedList {
public:
    StackLinkedList();
    void push(Item p);

private:
    StackLinkedList<Item>* node;
    Item data;
};

StackLinkedList.cpp

#include "StackLinkedList.h"

template <class Item>
StackLinkedList<Item>::StackLinkedList() {
    node = NULL;
}

template <class Item>
void StackLinkedList<Item>::push(Item p) {
    if(node == NULL) {
        StackLinkedList<Item>* nextNode;
        nextNode->data = p;
        node = nextNode;
    }else {
        node->push(p);
    }
}

main.cpp

#include "StackLinkedList.h"

int main() {
    StackLinkedList<int>* stack;

     stack->push(2);
}

Error details:

Undefined symbols for architecture x86_64:
  "StackLinkedList<int>::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.

aanrv
  • 2,159
  • 5
  • 25
  • 37
  • Also you should fix your include sentinel statement in `StackLinkedList.h` and move the `#endif ...` line to the end of your header file. Otherwise the compiler will attempt to redefine your class if you include the header file multiple times which could lead to build issues. – jammartin Mar 04 '21 at 16:59

1 Answers1

2

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.

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252