mac 使用 vscode 开发 cpp

123 阅读1分钟

前提:

使用 brew 安装了 gcc g++

或者

安装了 xcode

搭建 vscode cpp 开发环境

参考这里: code.visualstudio.com/docs/cpp/co…

# 1.  Install [Visual Studio Code on macOS](https://code.visualstudio.com/docs/setup/mac)

# 2. Install the [C++ extension for VS Code](https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools). You can install the C/C++ extension by searching for 'C++' in the Extensions view

# 3. ### [Ensure Clang is installed](https://code.visualstudio.com/docs/cpp/config-clang-mac#_ensure-clang-is-installed)

clang --version

如果 clang 没有安装执行下面命令安装

xcode-select --install


ok 开发环境就绪

1 新建一个文件夹 hello

在文件夹内新建 main.cpp


#include <iostream>

using namespace std;

int add(int x, int y);

int main()
{
    int n, m = 0;
    cin >> n >> m;
    cout << add(n, m) << endl;
}

add.cpp


int add(int x, int y)
{
    return x + y;
}

点击 运行按钮 ,

image.png 或者 command + shift + p 输入 c/c++:run

image.png

在项目根目录会生成 .vscode 文件夹,里面有一个 tasks.json

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

"${file}" 改为 "${fileDirname}/**.cpp","-g", 所在行的上一行新增一行 "-std=c++17",

完整内容如下:

{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: clang++ build active file",
            "command": "/usr/bin/clang++",
            "args": [
                "-fcolor-diagnostics",
                "-fansi-escape-codes",
                "-std=c++17",
                "-g",
                "${fileDirname}/**.cpp",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}

你还可以设置 语法提示

image.png

为 你想要的, image.png

如果想要语法提示生效,你要重新打开 vscode 或者 reload window

image.png