1 c++ linker c++11 visual-studio-code apple-silicon
过去一周我一直被这个问题困扰。当我使用 VS Code Insiders - Code Runner Extension 或命令: clang++ -std=c++14 main.cpp 编译代码时,出现以下错误:
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)
Run Code Online (Sandbox Code Playgroud)
但是,我能够使用下面的 Makefile 编译代码:
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
Run Code Online (Sandbox Code Playgroud)
如果我将 int main() {} 放入 linkedList.cpp 中,它也会起作用。我想也许存在某种链接器问题?我搜索错误的时候已经提到很多了。
这是代码: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;
}
Run Code Online (Sandbox Code Playgroud)
链接列表.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);
};
Run Code Online (Sandbox Code Playgroud)
链接列表.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;
}
Run Code Online (Sandbox Code Playgroud)
让我困惑的是,既然代码可以用Makefile编译,为什么不能用代码运行器编译呢?
只是一个快速更新:我在 CLion 上测试了代码并且它已编译,因此我将在 Vs Code 上重新安装代码运行器扩展,看看它是否解决了问题。
由于某种原因,MAC 上的 vscode 不会自动链接文件。您可能必须在终端中运行代码。
g++ main.cpp linkedList.cpp -o main
Run Code Online (Sandbox Code Playgroud)
然后就可以执行程序了
./main
Run Code Online (Sandbox Code Playgroud)
注意不要忘记与您正在编译的文件位于同一路径上
| 归档时间: |
|
| 查看次数: |
16795 次 |
| 最近记录: |