【问题标题】:Link error in Visual Studio Code with C++Visual Studio Code 中的 C++ 链接错误
【发布时间】:2021-07-02 17:10:12
【问题描述】:

我用 Catalina 在 Mac 上安装了 Visual Studio Code 来学习 C++。已安装扩展 C/C++C/C++ Extension PackC++ IntellisenseCMake ToolsCode Runner

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

再见.cpp:

#include <iostream>

void tryMe(int s) {
    std::cout << "ok";
}

再见.h:

void tryMe(int s);

你好.cpp:

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

int main() {
    tryMe(3);
    return 0;
}

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

$ 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)

我明白为什么会出现问题:编译不包括 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

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

【问题讨论】:

  • 编译器本身只处理translation units,这是一个单一的源文件及其所有包含的头文件。它不知道其他源文件,您必须显式构建和链接所有源文件。
  • 一旦您在项目中获得多个源文件,我建议您使用某种项目或构建系统来正确处理所有相关源文件的构建。 CMake 目前相当流行。有大量关于如何将 CMake 及其生成的构建文件集成到 Visual Studio Code 中的在线教程和示例。
  • @Someprogrammerdude 所以在 VSCode 上没有选项可以在我的项目上编译和运行多个文件,我必须在外部进行吗?我找不到控制 VSCode 上的编译参数的方法。
  • Visual Studio Code 在最基本的层面上只是一个纯文本编辑器。如果您想要内置项目管理和处理多个源文件,我建议您使用完整的 IDE,例如 Visual Studio Community?如果您愿意,还有其他使用 MinGW 的免费和开源 IDE。

标签: c++ visual-studio-code linker-errors


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2022-12-17
    • 1970-01-01
    • 2014-10-17
    • 2013-12-27
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    相关资源
    最近更新 更多