0

I have looked at other similar questions but I did not really understand the answers very well. I am getting this error:

In function main': C:/Users/Danny/ClionProjects/LinkedList/main.cpp:9: undefined reference tolinkList::linkList()' collect2.exe: error: ld returned 1 exit status

linkList.cpp:

#include <iostream>
#include <cstdlib>
#include "linkList.h"

using namespace std;

linkList::linkList()
{
    head = NULL;
    follow = NULL;
    trail = NULL;
}

void linkList::addNode(int dataAdd) 
{
    nodePtr n = new node; 
    n->next = NULL;
    n->data = dataAdd;

    if (head != NULL)
    {
        follow = head;
        while (follow->next != NULL)
        {
            follow = follow->next;
        }
    }
    else
    {
        head = n;
    }

}

void linkList::deleteNode(int nodeDel)
{
    nodePtr delPtr = NULL;
    follow = head;
    trail = head;

    while(follow != NULL)
    {
        trail = follow;
        follow = follow->next;
        if (follow->data == nodeDel)
        {
            delPtr = follow;
            follow = follow->next;
            trail->next = follow;
            delete delPtr;
        }
        if(follow == NULL)
        {
            cout << delPtr << " was not in list\n";
            delete delPtr; // since we did not use delPtr we want to delete it to make sure it doesnt take up memory
        }

    }

}

void linkList::printList()
{
    follow = head;
    while(follow != NULL)
    {
        cout << follow->data << endl;
        follow = follow->next;
    }


}

LinkList.h:

struct node {
    int data;
    node* next;
};

typedef struct node* nodePtr; 


class linkList
{ // the linkList will be composed of nodes

private:
    nodePtr head;
    nodePtr follow;
    nodePtr trail;

public:
    linkList();
    void addNode(int dataAdd);
    void deleteNode(int dataDel);
    void printList();
};

main.cpp:

#include <cstdlib>
#include "linkList.h"


using namespace std;

int main() {

    linkList myList;


    return 0;
}

I understand it has something to do with the way my files are linked, when I change #include linkList.h to #include linkList.cpp in my main file it works fine why is this? I have another similar program that is a binary search tree that works perfectly and has basically the same type of set up. So my question is how do I fix it? why is it happening?

1 Answers1

2

You need to add linkList.cpp to your project if you're using a build system/IDE that does it automatically. You need to either:

  1. compile it separately with g++ -c linkList.cpp -o linkList.o
  2. and then compile and link the final executable g++ main.cpp linkList.o

or compile them both directly (infeasible for larger projects): g++ main.cpp linkList.cpp

Including a .cpp file is a bad idea and you shouldn't have to do this.

krzaq
  • 16,240
  • 4
  • 46
  • 61