在VSCODE下设置C++编译环境

VSCODE是由微软开发的一种轻型多用途编译器,可以下载C++插件来编译gcc的控制台程序。作者写这篇文章时参考了官方文档,照此此文档进行操作是可以完成VSCODE的C++环境配置的。文档地址如下所示:Get Started with C++ and Mingw-w64 in Visual Studio CodeConfiguring the C++ extension in Visual Studio Code to target g++ and gdb on a Mingw-w64 installationhttps://code.visualstudio.com/docs/cpp/config-mingw在此链接下载VSCODE。

Download Visual Studio Code - Mac, Linux, WindowsVisual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows. Download Visual Studio Code to experience a redefined code editor, optimized for building and debugging modern web and cloud applications.https://code.visualstudio.com/download下载VSCODE之后,运行这款软件。

1、安装

 如上图所示,点击“步骤1.”,或者在PC键盘下按:Ctrl+Shift+X键,打开VSCODE的Extensions选项。在搜索栏中输入“C++”搜索,找到Microsoft公司的插件“C/C++”,进行安装。

2、建立工作文件夹

  1. 在PC上建立一个文件夹。比如:C:\vc98_workspace\console
  2. 如上图所示,在VSCODE中点击File->Open Floder...,选择C:\vc98_workspace\console文件夹。

3、安装GCC编译器

作者使用的GCC编译器复用了DEV-C++自带的的编译器。DEV-C++是一款不再维护的中型C++IDE。支持gcc(g++)开发WINDOWS WIN32应用程序。Dev-C++下载地址是:Dev-C++ - DownloadDev-C++, free and safe download. Dev-C++ latest version: Free Open-Source IDE for Windows. Dev-C++ is a free integrated development program for Windowhttps://bloodshed-dev-c.en.softonic.com/

 4、设置C++编译环境

#include <iostream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    vector<string> msg {"Hello", "C++", "World", "from", "VS Code", "and the C++ extension!"};

    for (const string& word : msg)
    {
        cout << word << " ";
    }
    cout << endl;
}

一个cpp文件如上所示。把这个文件命名为"first.cpp",保存到C:\vc98_workspace\console文件夹中。

{
    "tasks": [
      {
        "type": "cppbuild",
        "label": "C/C++: g++.exe build active file",
        "command": "D:/Dev-Cpp/MinGW64/bin/gcc.exe",
        "args": ["-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe"],
        "options": {
          "cwd": "${fileDirname}"
        },
        "problemMatcher": ["$gcc"],
        "group": {
          "kind": "build",
          "isDefault": true
        },
        "detail": "D:/Dev-Cpp/MinGW64/bin/gcc.exe"
      }
    ],
    "version": "2.0.0"
  }

在VSCODE中选择Terminal > Configure Default Build Task选项,新建一个tasks.json文件。tasks.json文件的名称是固定的。将tasks.json文件的内容替换成以上内容。

 在task.json这个json文件中其中:

  1. "command": "D:/Dev-Cpp/MinGW64/bin/gcc.exe"的value值"command",对应key值D:/Dev-Cpp/MinGW64/bin/gcc.exe表示DEV-C++自带的的gcc编译器的绝对路径。
  2. "args": ["-g", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe"]的value值"args",对应的key值${fileDirname}\\${fileBasenameNoExtension}表示VSCODE调用gcc.exe把源相对路径文件.\first.cpp,生成绝对路径的exe程序。在这里,生成的绝对路径exe程序是:C:\vc98_workspace\console\first.exe
  3. VSCODE自带的变量${fileDirname}表示相对源文件.\first.cpp所在的文件夹:C:\vc98_workspace\console\
  4. ${fileBasenameNoExtension}表示去除后缀的“文件字符串”。如first.cpp的去除后缀的“文件字符串”是"first"(不带双引号)。
  5. "detail": "D:/Dev-Cpp/MinGW64/bin/gcc.exe"的value值"detail"要和value值"command"对应的key值一致。

猜你喜欢

转载自blog.csdn.net/lihongtao8209/article/details/121142241