0

Thanks for your attention! I am a new hand in C++ and this drives me crazy. Here is the compile result:

$ g++ -std=c++11 main.cpp Node.cpp
C:\Users\Sen\AppData\Local\Temp\ccsNgEyE.o:main.cpp:(.text+0x29): undefined reference to `Node<int>::Node()'
C:\Users\Sen\AppData\Local\Temp\ccsNgEyE.o:main.cpp:(.text+0x43): undefined reference to `Node<int>::setItem(int const&)'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: 
C:\Users\Sen\AppData\Local\Temp\ccsNgEyE.o: bad reloc address 0x0 in section `.ctors'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: final link failed: Invalid operation
collect2.exe: error: ld returned 1 exit status

And here are my files: Node.h:

#ifndef NODE_H
#define NODE_H
template <class ItemType>
class Node{
private:
    ItemType item;
    Node<ItemType>* next;
public:
    Node();
    Node(const ItemType& anItem);
    Node(const ItemType& anItem, Node<ItemType>* nextNodePtr);
    void setItem(const ItemType& anItem);
    void setNext(const Node<ItemType>* nextNodePtr);
    ItemType getItem() const;
    Node<ItemType>* getNext() const;    
};
#endif

Node.cpp:

#include "Node.h"
using namespace std;

template <class ItemType>
Node<ItemType>::Node(){
    next = nullptr;
}

template <class ItemType>
Node<ItemType>::Node(const ItemType& anItem){
    item = anItem;
    next = nullptr;
}

template <class ItemType>
Node<ItemType>::Node(const ItemType& anItem, Node<ItemType>* nextNodePtr){
    item = anItem;
    next = nextNodePtr;
}

template <class ItemType>
void Node<ItemType>::setItem(const ItemType& anItem){
    item = anItem;
}

template <class ItemType>
void Node<ItemType>::setNext(const Node<ItemType>* nextNodePtr){
    next = nextNodePtr;
}

template <class ItemType>
ItemType Node<ItemType>::getItem() const{
    return item;
}

template <class ItemType>
Node<ItemType>* Node<ItemType>::getNext() const{
    return next;
}

My main.cpp file:

#include <iostream>
#include <vector>
#include "Node.h"

int main(){ 
    Node<int>* node1 = new Node<int>();
    node1->setItem(1);  
}

I simply don't know why... in g++ command I added in Node.cpp and in Node.cpp there is obviously implementations of the constructor and method. Thanks for your attention!

  • 2
    possible duplicate of [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file), more similar [undefined reference to template function](http://stackoverflow.com/questions/10632251/undefined-reference-to-template-function?lq=1) – Mohit Jain Mar 23 '15 at 06:04
  • Thanks! This helped me a lot. Thanks again!!! – SenseYang Mar 25 '15 at 02:57
  • I am glad it helped you. – Mohit Jain Mar 25 '15 at 04:55

0 Answers0