I've been stuck on this issue in the past week. when I compiled the code with the VS Code Insiders - Code Runner Extension or the command: clang++ -std=c++14 main.cpp, it gives me the below error:
Undefined symbols for architecture arm64:
"LinkedList::insertHead(int)", referenced from:
_main in main-6d6a24.o
"LinkedList::insertTail(int)", referenced from:
_main in main-6d6a24.o
"operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, LinkedList const&)", referenced from:
_main in main-6d6a24.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
However, I was able to compile the code with the Makefile below:
all: main
main: main.o linkedList.o
clang++ -std=c++14 -o $@ $^
main.o: main.cpp linkedList.h
clang++ -std=c++14 -c $<
linkedList.o: linkedList.cpp linkedList.h
clang++ -std=c++14 -c $<
clean:
rm -f main *.o
rm -f linkedList *.o
And also it would work if I put the int main() {} inside the linkedList.cpp. I guess maybe there are some kind of linker issue? It's been mentioned a lot when I searched the error.
Here is the code: main.cpp:
#include "linkedList.h"
#include <iostream>
int main() {
LinkedList l;
LinkedList l2;
for (int i = 0; i < 10; i++) {
l.insertHead(i);
}
for (int i = 0; i < 10; i++) {
l2.insertTail(i);
}
std::cout << l << std::endl;
std::cout << l2 << std::endl;
return 0;
}
linkedList.h:
#include <iostream>
struct Node {
int data;
Node *next = nullptr;
};
class LinkedList {
private:
Node *head;
Node *tail;
void inserFirst(int);
Node *createNode(int);
public:
void insertHead(int);
void insertTail(int);
friend std::ostream &operator<<(std::ostream &out, const LinkedList &list);
};
linkedList.cpp:
#include "linkedList.h"
void LinkedList::inserFirst(int item) {
Node *n = createNode(item);
head = n;
tail = n;
}
Node* LinkedList::createNode(int item) {
Node *n = new Node;
n->data = item;
n->next = nullptr;
return n;
}
void LinkedList::insertHead(int item) {
if (head == nullptr) {
inserFirst(item);
} else {
Node *n = createNode(item);
n->next = head;
head = n;
}
}
void LinkedList::insertTail(int item) {
if (head == nullptr) {
inserFirst(item);
} else {
Node *n = createNode(item);
tail->next = n;
tail = n;
}
}
std::ostream &operator<<(std::ostream &out, const LinkedList &list) {
Node *n = list.head;
while (n != nullptr) {
out << n->data;
n = n->next;
}
return out;
}
What made me confused is since the code can be compiled with the Makefile, why wouldn't it be compiled with the code runner?
Just a quick update: I tested the code on CLion and it was compiled, so I'm gonna reinstall the code runner extension on Vs Code to see if it fixes the problem.