Mac OS - VS Code Insiders - Code Runner:架构 arm64 的未定义符号

时间:2021-03-06 03:54:24

标签: c++ c++11 visual-studio-code linker 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)

但是,我能够使用下面的 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

而且,如果我将 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;
}

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;
}

让我困惑的是,既然代码可以用Makefile编译,为什么不能用code runner编译呢?

只是一个快速更新:我在 CLion 上测试了代码并编译了它,所以我将在 Vs Code 上重新安装代码运行器扩展,看看它是否能解决问题。

1 个答案:

答案 0 :(得分:0)

找到了一个“临时”的答案: 在 Code-runner: Executor Map 中,在设置中进行编辑。 json,我改了

"cpp": "cd $dir && clang++ -std=c++14 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt",

通过在 $fileName 之后添加linked_list.cpp(实现文件)

"cpp": "cd $dir && clang++ -std=c++14 $fileName linked_list.cpp -o $fileNameWithoutExt && $dir$fileNameWithoutExt",