【问题标题】:How to set up Visual Studio Code on Mac for linking multiple files during build?如何在 Mac 上设置 Visual Studio Code 以在构建期间链接多个文件?
【发布时间】:2021-10-05 01:02:36
【问题描述】:

我正在学习 C++,介绍 CS 类,我们现在开始为 OOP 实现数据抽象。我需要将类定义隐藏在单独的 .cpp 文件中并使用头文件。到目前为止,我一直在我的 Macbook pro 中使用 VSCode 中的默认设置来创建单个文件程序,所以我决定创建一个测试程序以确保在创建整个项目之前编译、包含和链接能够正常工作,但是现在当我尝试构建程序时,我收到一个错误。我已经尝试了几天使用潜在的解决方案来解决问题,但没有成功。我希望这里有人能带领我走向正确的方向。

我已经包含了 3 个测试文件(test.cpp、test.h 和 testImp.cpp)、c_cpp_properties.json、launch.json、settings.json 和 task.json 文件的内容以及错误的内容消息。

任何帮助设置 VSCode 以完成包括头文件将不胜感激,因为我将有更多具有此要求的项目。

谢谢你,詹姆斯。

test.cpp

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

using namespace std;

int main()
{
    cout << testCalculation(5, 7) << endl;
    cout << endl;
    return 0;
}

测试.h

#ifndef test_h
#define test_h

int testCalculation(int, int);

#endif /* test_h */

testImp.cpp

#include "test.h"

int testCalculation(int x, int y) {
int sum = int();
    sum = x + y;
    return sum;
};

c_cpp_properties.json

    "configurations": [
        {
            "name": "Mac",
            "includePath": [
                "${default}",
                "${workspaceFolder}/**"
            ],
            "compilerPath": "/usr/bin/g++",
            "cStandard": "c17",
            "cppStandard": "c++11",
            "intelliSenseMode": "${default}"
        }
    ],
    "version": 4
}

launch.json

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "g++ - Build and debug active file",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "lldb",
            "preLaunchTask": "C/C++: g++ build active file"
        }
    ]
}

setting.json

{
    "files.associations": {
        "iostream": "cpp"
    }
}

task.json

{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}

错误

Starting build...
/usr/bin/g++ -fdiagnostics-color=always -g /Users/jamesreal/cpp/cs-2/project-1/test.cpp -o /Users/jamesreal/cpp/cs-2/project-1/test
Undefined symbols for architecture x86_64:
  "testCalculation(int, int)", referenced from:
      _main in test-5cbf98.o
ld: symbol(s) not found for architecture x86_64

clang: error: linker command failed with exit code 1 (use -v to see invocation)

【问题讨论】:

  • 您的错误在这里:"${file}", 这意味着您只想将活动文件构建到可执行文件中。该文档告诉您如何修复以在此处构建所有文件:https://code.visualstudio.com/docs/cpp/config-clang-mac#_modifying-tasksjson
  • @drescherjm,我非常感谢你。我花了很多时间试图解决这个问题。我知道答案在某处的文档中,但我不知道去哪里找。我感激你。谢谢你,谢谢你,谢谢你。保持健康。
  • 我花了一些时间才找到,但我相信上面的链接是合理的重复。
  • @drescherjm,是的,这有帮助。谢谢你。在那篇文章中有几个来源我也会审查,但你的第一个答案提供了一个解决方案。我感谢后续跟进并提供进一步的资源,这些资源可以更深入地了解问题。你摇滚!

标签: c++ json visual-studio-code g++ include-path


【解决方案1】:

-1.兄弟。

您的配置文件是用于构建、编译和调试的Only one file,而不是您想要的multiple sources files'

0.初见

首先,您将“settings.json”命名为“setting.json”是错误的;

另外,您将“tasks.json”命名为“task.json”是错误的。

1.你的项目

正如您的项目 Architecture test 所示,

test

|

|_.vscode

|     |__c_cpp_properties.json

|     |__launch.json

|     |__settings.json

|     |__tasks.json

|__test.cpp

|__test.h

|__testImp.cpp

3.解决方案:

设置多个源文件构建的三种方式

VSCode.

一种是将终端命令写入“settings.json”和

tasks.json”+“launch.json”+“c_cpp_properties.json”;

二是通过make写“Makefile”文件来做到这一点;

三是通过CMake写“CMakeList.txt”来做到这一点。

现在,我只分享第一个解决方案。

4.我在mac上使用VSCode的工作区环境

我只是用Clang9.0.0编译,Code Runner v0.11.6

运行程序,CodeLLDB v1.4.5进行调试,C/C++ Clang Command Adopter

v0.2.4(VSCode Extension) 在 mac 上使用 VSCode 提供静态检测。

可能你用cpptools(cpptools是用来调试的,这个CPPtools

还有CodeLLDB 冲突。 ),没关系,改一下就行了

在“launch.json”中将“type”从“lldb”转换为“cppdbg”。

5.我的解决方案

这是同一文件夹下多个源文件在mac上用VSCode编译调试的问题。

我总是首先配置settings.json。显示如下:

settings.json”,请注意“code-runner.executorMap”。

重要通知:这是“settings.json”。不是“setting.json”!!!

{
    "files.defaultLanguage": "c++",
    "editor.suggest.snippetsPreventQuickSuggestions": false,
    "editor.acceptSuggestionOnEnter": "off",
    "code-runner.runInTerminal": true,
    "code-runner.executorMap": {
    // 3.Mutiple sourece C/C++ files under same folder build, compile, debug...
    // if put main.o and debug folder into the current directory "./"
    "c": "cd $dir && clang -std=c11 -stdlib=libc++  $dir/*.c  -o $dir/$fileNameWithoutExt && $dir/$fileNameWithoutExt", // Have changed
    "cpp": "cd $dir && clang++ -std=c++11 -stdlib=libc++  $dir/*.cpp -o $dir/$fileNameWithoutExt && $dir/$fileNameWithoutExt" // Have changed
    },
    "code-runner.saveFileBeforeRun": true,
    "code-runner.preserveFocus": false,
    "code-runner.clearPreviousOutput": false,
    "code-runner.ignoreSelection": true,
    "C_Cpp.clang_format_sortIncludes": true,
    "editor.formatOnType": true,
    "clang.cxxflags": [
        "-std=c++11"
    ],
    "clang.cflags": [
        "-std=c11"
    ],
    "C_Cpp.updateChannel": "Insiders",
    "[makefile]": {
        "editor.insertSpaces": true
    },
    "C_Cpp.default.includePath": [
        "${workspaceFolder}"
    ],
    "clang.completion.enable": true
}

如果您使用gcc/g++,只需将clang/clang++ 更改为那些。

如果这行代码需要更改或起作用,我添加注释

// Have changed”。只是注意到那行代码!请!

tasks.json”:你知道,那是“tasks.json”!!!不是“task.json”。

{
  "version": "2.0.0",
  "tasks": [
    {
      "type": "shell",
      "label": "Compile With clang++",
      //"command": "clang++",/usr/bin/clang++
      "command": "/usr/bin/clang++",
      "args": [
        "-std=c++11",
        "-stdlib=libc++",
        // My project fitBodyBootCamp were under 
        // /Users/marryme/VSCode/CppProject/fitBodyBootCamp
        // So ${workspcaeFolder} also were
        // /Users/marryme/VSCode/CppProject/fitBodyBootCamp
        // all the *.cpp files were under
        // /Users/marryme/VSCode/CppProject/fitBodyBootCamp
        "${workspaceFolder}/*.cpp", // Have changed
        "-o",
        // Thanks those chiense website bloggers!
        // 1.mac vscode compile c++ multi-directory code demo
        // https://blog.csdn.net/fangfengzhen115/article/details/121496770?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_baidulandingword~default-4.pc_relevant_default&spm=1001.2101.3001.4242.3&utm_relevant_index=7
        // 2.Compile and debug c++ multi-folder project under VSCode (non-makefile)
        // https://blog.csdn.net/BaiRuichang/article/details/106463035
        // I also put the main.o under my current workspace directory
        // This after "-o"  is the target file test.o or test.out or test
        "${workspaceFolder}/${fileBasenameNoExtension}", // Have changed
        "-I",
        // This after "-I" if the include files directory
        "${workspaceFolder}", // Have changed
        "-Wall",
        "-g"
      ],
      "options": {
        // "cwd" is the source files directory
        "cwd": "${workspaceFolder}" // Have changed
      },
      "group": {
        "kind": "build",
        "isDefault": true
      }
    }
  ]
}

launch.json”:

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug With LLDB",
      "type": "lldb",
      "request": "launch",
      // "program" is the target file diretory
      "program": "${workspaceFolder}/${fileBasenameNoExtension}", // Have changed
      "args": [],
      "stopAtEntry": true,
      //"cwd": "${workspaceFolder}/../build",// Have changed
      //"cwd": "${fileDirName}", ${workspaceFolder}/../build
      // Changes the current working directory directive ("cwd") to the folder
      // where main.cpp is.
      // This "cwd" is the same as "cwd" in the tasks.json 
      // That's the source files directory
      "cwd": "${workspaceFolder}", // Have changed
      "environment": [],
      "externalConsole": false,
      "preLaunchTask": "Compile With clang++"
    }
  ]
}

现在,“c_cpp_properties.json”

{
  "configurations": [
    {
      "name": "Mac",
      "includePath": [
        // This is the include files directory
        "${workspaceFolder}/**", // Have Change
        "/Library/Developer/CommandLineTools/usr/include",
        "/Library/Developer/CommandLineTools/usr/lib/clang/9.0.0/include",
        "/usr/local/include",
        "/Library/Developer/CommandLineTools/usr/include/c++/v1",
        "/usr/include"
      ],
      "defines": [],
      "macFrameworkPath": [
        "/System/Library/Frameworks",
        "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks",
        "/Library/Frameworks"
      ],
      "compilerPath": "/usr/bin/clang",
      "cStandard": "c11",
      "cppStandard": "c++11",
      "intelliSenseMode": "clang-x64"
    }
  ],
  "version": 4
}

注意事项:

如果你的程序包含,你只需要修改Include path设置

不在您的工作区或标准库路径中的头文件。

特别是:"includePath": [ "/Library/Developer/CommandLineTools/usr/lib/clang/9.0.0/include"]

如果你分离的命令行工具的 Clang 版本是9.0.0,复制这个程序

直接。

如果没有,只需使用此命令检查您分离的 Clang 版本

命令行工具:

cd /Library/Developer/CommandLineTools/usr/lib/clang/ &amp;&amp; ls

可能显示如下:9.0.09.1.010.0.0 或 X.X.X。正如这可能表明的那样,

您分离的命令行工具的 Clang 版本是 9.0.09.0.1

10.0.0X.X.X。只需替换我的9.0.0

如果您没有单独的命令行工具,只需安装a separated command

适用于您的 Mac 的线工具,具体取决于您的 macOS 系统。

我会通过添加文件来添加这5个文件。

结束。

最后,

如果需要单独构建多个源文件,

那种架构就是喜欢:

fitBody

|

|_.vscode

|     |__c_cpp_properties.json

|     |__launch.json

|     |__settings.json

|     |__tasks.json

|__build

|__inc

|     |__fitbody.h

|__src

     |__fitbody.cpp
 
     |__main.cpp

请参考 GitHub Gist 中的Separated Multiple CXX ManuallyVScode(mac)。

或者,参考Separated Multiple CXX Manually VScode(mac) 来自 GitHub。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-17
    • 2015-07-21
    • 2017-02-02
    • 2016-01-06
    • 2022-08-08
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    相关资源
    最近更新 更多