Every time I have a class in a header file and I'm using the class in the source file, I get the same error. Doesn't matter which class or which project it is.
I am trying to insert a new node onto the head of a linked list data structure.
Right now I have a pretty simple header file main.h
:
namespace linkedlistofclasses {
class Node {
public:
Node();
Node(int value, Node *next);
//Constructor to initialize a node
int getData() const;
//Retrieve value for this node
Node *getLink() const;
//Retrieve next Node in the list
void setData(int value);
//Use to modify the value stored in the list
void setLink(Node *next);
//Use to change the reference to the next node
private:
int data;
Node *link;
};
typedef Node* NodePtr;
}
My source file main.cpp
looks like this:
#include <iostream>
#include "main.h"
using namespace std;
using namespace linkedlistofclasses;
void head_insert(NodePtr &head, int the_number) {
NodePtr temp_ptr;
//The constructor sets temp_ptr->link to head and
//sets the data value to the_number
temp_ptr = new Node(the_number, head);
head = temp_ptr;
}
int main() {
NodePtr head, temp;
//Create a list of nodes 4->3->2->1->0
head = new Node(0, NULL);
for (int i = 1; i < 5; i++) {
head_insert(head, i);
}
//Iterate through the list and display each value
temp = head;
while (temp !=NULL) {
cout << temp->getData() << endl;
temp = temp->getLink();
}
//Delete all nodes in the list before exiting
//the program.
temp = head;
while (temp !=NULL) {
NodePtr nodeToDelete = temp;
temp = temp->getLink();
delete nodeToDelete;
}
return 0;
}
My problem is that I get these compilation errors:
Undefined symbols for architecture x86_64:
"linkedlistofclasses::Node::Node(int, linkedlistofclasses::Node*)", referenced from:
head_insert(linkedlistofclasses::Node*&, int) in main.o
_main in main.o
"linkedlistofclasses::Node::getData() const", referenced from:
_main in main.o
"linkedlistofclasses::Node::getLink() const", 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)
If I run the code without a using a class, writing everything in the source file main.cpp
, there is no problem.
But no matter how I write a class, I always get some variant of this error.