Visual Studio Code 与 C++ 的链接错误

jos*_*eph 5 c++ linker-errors visual-studio-code

为了学习 C++,我在 Mac 上安装了带有 Catalina 的 Visual Studio Code。安装的扩展C/C++C/C++ Extension PackC++ IntellisenseCMake ToolsCode Runner

为了测试 VSCode,我尝试运行以下代码:

再见.cpp:

#include <iostream>

void tryMe(int s) {
    std::cout << "ok";
}
Run Code Online (Sandbox Code Playgroud)

再见.h:

void tryMe(int s);
Run Code Online (Sandbox Code Playgroud)

你好.cpp:

#include <iostream>
#include "bye.h"

int main() {
    tryMe(3);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但它不会运行,因为它会导致编译错误:

$ cd "/Users/x/Workspace/LearnCPP/" && g++ hello.cpp -o hello && "/Users/x/Workspace/LearnCPP/"hello
Undefined symbols for architecture x86_64:
  "tryMe(int)", referenced from:
      _main in hello-ef5e99.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Run Code Online (Sandbox Code Playgroud)

我明白为什么会出现问题:编译不包含该bye.cpp文件,因此它无法识别该函数。如果我使用终端通过终端进行编译,g++ hello.cpp bye.cpp -o hello它会编译良好并按预期运行。

c_cpp_properties.json:

{
    "configurations": [
        {
            "name": "Mac",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [],
            "macFrameworkPath": [
                "/System/Library/Frameworks",
                "/Library/Frameworks"
            ],
            "compilerPath": "/usr/bin/clang++",
            "cStandard": "c17",
            "cppStandard": "c++17",
            "intelliSenseMode": "macos-clang-x64"
        }
    ],
    "version": 4
Run Code Online (Sandbox Code Playgroud)

我搜索并看到了一些提到“任务”文件的文章,但无法理解如何实现它或它来自哪里。

小智 4

我搜索并看到了一些提到“任务”文件的文章,但无法理解如何实现它或它来自哪里。

我也遇到了这个问题,发现这个 Visual Studio Code 文档显示,在 中task.json,必须将命令参数之一从 更改为"${file}""${workspaceFolder}/*.cpp"其他命令参数中才能构建所有.cpp文件。