Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined reference to `LinkedList<int>::push_front(int) [duplicate]

Possible Duplicate:
Why do I get “unresolved external symbol” errors when using templates?

LinkedList.h

#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include<iostream>

template<class T> class LinkedList;

//------Node------
template<class T>
class Node {
private:
    T data;
    Node<T>* next;
public:
    Node(){data = 0; next=0;}
    Node(T data);
    friend class LinkedList<T>;

};


//------Iterator------
template<class T>
class Iterator {
private:
    Node<T> *current;
public:

    friend class LinkedList<T>;
    Iterator operator*();
 };

//------LinkedList------
template<class T>
class LinkedList {
private:
    Node<T> *head;


public:
    LinkedList(){head=0;}
    void push_front(T data);
    void push_back(const T& data);

    Iterator<T> begin();
    Iterator<T> end();

};



#endif  /* LINKEDLIST_H */

LinkedList.cpp

#include "LinkedList.h"
#include<iostream>


using namespace std;

//------Node------
template<class T>
Node<T>::Node(T data){
    this.data = data;
}


//------LinkedList------
template<class T>
void LinkedList<T>::push_front(T data){

    Node<T> *newNode = new Node<T>(data);

    if(head==0){
        head = newNode;
    }
    else{  
        newNode->next = head;
        head = newNode;
    }    
}

template<class T>
void LinkedList<T>::push_back(const T& data){
    Node<T> *newNode = new Node<T>(data);

    if(head==0)
        head = newNode;
    else{
        head->next = newNode;
    }        
}


//------Iterator------
template<class T>
Iterator<T> LinkedList<T>::begin(){
    return head;
}

template<class T>
Iterator<T> Iterator<T>::operator*(){

}

main.cpp

#include "LinkedList.h"

using namespace std;


int main() {
    LinkedList<int> list;

    int input = 10;

    list.push_front(input); 
}

Hi, I am fairly new at c++ and I am trying to write my own LinkedList using templates.

I followed my book pretty closely and this is what I got. I am getting this error though.

/main.cpp:18: undefined reference to `LinkedList::push_front(int)'

I have no clue why, any ideas?

like image 574
Instinct Avatar asked Mar 06 '26 15:03

Instinct


1 Answers

You are using templates in your Program. When you use templates, you have to write the code and the headers in the same file because the compiler needs to generate the code where it is used in the program.

You can do either this or include #inlcude "LinkedList.cpp" in main.cpp

This question might help you. Why can templates only be implemented in the header file?

like image 74
Coding Mash Avatar answered Mar 09 '26 06:03

Coding Mash