I just wrote a simple program that creates a linked list. When I wrote the entire program in just one file (main.cpp) the program compiled and ran fine. However, when I separated the program into a header file, an implementation file, and main, it doesn't work. I get the error "undefined reference to List::AddNode(int). I don't understand why...
header file
#ifndef LINKEDLIST_H_INCLUDED
#define LINKEDLIST_H_INCLUDED
#include <iostream>
using namespace std;
class List
{
public:
List();
void AddNode(int addData);
void DeleteNode(int deldata);
void PrintList();
private:
struct Node
{
int data;
Node* next;
};
Node* head;
Node* curr;
Node* temp;
};
#endif // LINKEDLIST_H_INCLUDED
List.cpp
#include <cstdlib>
#include <iostream>
#include "List.h"
using namespace std;
List::List()
{
head = nullptr;
curr = nullptr;
temp = nullptr;
}
void List::AddNode(int addData)
{
nodePtr n = new Node;
n->next = nullptr;
n->data = addData;
if(head !=nullptr)
{
curr = head;
while(curr->next!=nullptr)
{
curr = curr->next; //This while loop advances the curr pointer to the next node in the list
}
curr->next = n; //now the last node in the list points to the new node we created. So our new node is now the last node
}
else
{
head = n;
}
}
void List::DeleteNode(int delData)
{
Node* delPtr = nullptr; //created a deletion pointer and set it equal to nothing (it's not pointing to anything)
temp = head;
curr = head;
while(curr != nullptr && curr->data !=delData)
{
temp = curr;
curr = curr->next;
}
if(curr==nullptr)
{
cout << delData << " was not in the list \n"
delete delPtr;
}
else
{
delPtr = curr;
curr = curr->next;
temp->next = curr;
delete delPtr;
cout << "the value " << delData << "was deleted \n";
}
}
void List::PrintList()
{
head = curr;
while(curr!=nullptr)
{
cout<<curr->data<<endl;
curr = curr->next;
}
}
main.cpp
#include <iostream>
#include <cstdlib>
#include "List.h"
using namespace std;
int main()
{
List crisa;
crisa.AddNode(5);
}
I get the error in the main.cpp file when I try to call the function AddNode. I don't know why, could it be a compiler issue?