I'm doing some linked list practices in C++ and created a simple class for the single linked list. When I try to include the header-file in the main program however I get an undefined reference error. If I include the .cpp file however it works as I want it to.
It's been a while since I last coded in C++ and I can't for the love of me figure out what's wrong. Some help would be deeply appreciated. I'm using Windows Termnial with git-bash interface and g++ -std=c++11. The code is included below!
//The main file .cpp
#include "SingleNode.h"
int main() {
SingleNode* tail = new SingleNode(2);
SingleNode* head = new SingleNode(1, tail);
head->print();
return 0;
}
//SingleNode.h
#ifndef SINGLENODE_H
#define SINGLENODE_H
class SingleNode {
public:
int val;
SingleNode* next;
SingleNode();
SingleNode(int x);
SingleNode(int x, SingleNode* next);
void print();
};
#endif
//SingleNode.cpp
#include "SingleNode.h"
#include <iostream>
using namespace std;
SingleNode::SingleNode() : val(0), next(nullptr) {}
SingleNode::SingleNode(int x) : val(x), next(nullptr) {}
SingleNode::SingleNode(int x, SingleNode* next) : val(x), next(next) {}
void SingleNode::print() {
if (this->next != nullptr) {
cout<<this->val<<"->";
this->next->print();
} else {
cout<<this->val<<"->"<<"null"<<endl;
}
}
When run:
$ g++ -std=c++11 LinkedList.cpp -o LinkedList.exe
C:\AppData\Local\Temp\ccEbmcRt.o:LinkedList.cpp:(.text+0x30): undefined reference to `SingleNode::SingleNode(int)'
C:\AppData\Local\Temp\ccEbmcRt.o:LinkedList.cpp:(.text+0x59): undefined reference to `SingleNode::SingleNode(int, SingleNode*)'
C:\AppData\Local\Temp\ccEbmcRt.o:LinkedList.cpp:(.text+0x69): undefined reference to `SingleNode::print()'
collect2.exe: error: ld returned 1 exit status
If I instead #include "SingleNode.cpp"
it works fine.