macos上使用vscode进行c/c++编程

参考教程

C/C++ for Visual Studio Code

https://code.visualstudio.com/docs/languages/cpp

https://code.visualstudio.com/docs/cpp/config-clang-mac

安装扩展

安装本地compiler

macOS 上可以直接使用gcc或者clang

可以使用下面两条命令来验证 compiler 是否安装成功

songfangtaodeMacBook-Pro:~ flik$  clang
clang: error: no input files
songfangtaodeMacBook-Pro:~ flik$ clang -v
Apple clang version 13.0.0 (clang-1300.0.27.3)
Target: x86_64-apple-darwin21.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

创建项目

mkdir c_workspace
cd c_workspace
mkdir hello
cd hello
cd .

添加配置

在结束这一步骤后,在工作文件夹的.vscode下将至少生成以下三个文件:

生成活动文件tasks.json

Terminal > Configure Default Build Task

选择C/C++ clang++,这一步将会在.vscode文件夹内生成tasks.json

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",
  "tasks": [
    {
      "type": "shell",
      "label": "clang++ build active file",
      "command": "/usr/bin/clang++",
      "args": [
        "-std=c++17",
        "-stdlib=libc++",
        "-g",
        "${file}",
        "-o",
        "${fileDirname}/${fileBasenameNoExtension}"
      ],
      "options": {
        "cwd": "${workspaceFolder}"
      },
      "problemMatcher": ["$gcc"],
      "group": {
        "kind": "build",
        "isDefault": true
      }
    }
  ]
}

生成扩展配置文件ccppproperties.json

Command Palette输入c++

选择C/C++: Edit Configurations (UI)

修改cppStandard属性为:

"cppStandard": "c++17",
{
  "configurations": [
    {
      "name": "Mac",
      "includePath": ["${workspaceFolder}/**"],
      "defines": [],
      "macFrameworkPath": [
        "/Library/Developer/CommandLineTools/SDKs/MacOSX12.1.sdk/System/Library/Frameworks"
      ],
      "compilerPath": "/usr/bin/clang",
      "cStandard": "c17",
      "cppStandard": "c++17",
      "intelliSenseMode": "macos-clang-x64"
    }
  ],
  "version": 4
}

创建Debug文件launch.json

选择 Run > Add Configuration… > C++ (GDB/LLDB),随后选择clang++ build and debug active file.

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": "clang++ - Build and debug active file",
      "type": "cppdbg",
      "request": "launch",
      "program": "${fileDirname}/${fileBasenameNoExtension}",
      "args": [],
      "stopAtEntry": true,
      "cwd": "${workspaceFolder}",
      "environment": [],
      "externalConsole": false,
      "MIMode": "lldb",
      "preLaunchTask": "clang++ build active file"
    }
  ]
}

修改clang的标准,以支持C++17

修改Clang:Cxxflags-std=c++17

构建hello.cpp

⇧⌘B或者 Terminal > Run Build Task.

进入hello/src文件,执行

./hello

flik's blog

© 2024 flik's blog | Powerd by Static | 备案号:浙ICP备2021025060号-1

GitHub