21xrx.com
2024-09-20 00:12:49 Friday
登录
文章检索 我的文章 写文章
Visual Studio Code如何运行C++代码?
2023-07-01 06:31:48 深夜i     --     --
Visual Studio Code 运行 C++ 代码

Visual Studio Code是一款非常方便的代码编辑器,它支持多种编程语言,包括C++。对于初学者来说,在Visual Studio Code中运行C++代码可能会有些困惑,但是只要按照以下步骤进行操作,就可以轻松地运行C++代码。

第一步:安装C++编译器

Visual Studio Code不包含C++编译器,因此,您需要先安装C++编译器。可以选择安装MSYS2或MinGW-w64编译器。建议选择MinGW-w64,因为它更简单方便。

第二步:安装C/C++扩展程序

在Visual Studio Code中,需要安装C/C++扩展程序以支持C++编程。可以在“扩展”选项卡中搜索“C/C++”,然后选择“C/C++”扩展程序进行安装。安装完成后,重新启动Visual Studio Code。

第三步:创建C++项目

打开Visual Studio Code,点击“文件”菜单,选择“新建文件夹”,然后在文件夹中添加C++源代码文件。可以在文件夹中创建一个名为“hello.cpp”的文件。然后在新文件中输入以下代码:

#include

using namespace std;

int main()

World!" << endl;

  return 0;

第四步:编译C++程序

在Visual Studio Code中,使用快捷键“Ctrl + Shift + P”调出命令面板,在命令面板中输入“C/C++:Edit configurations(编辑配置)”,然后选择“Debug: C++ Launch(调试:C++启动)”或“C++(GDB)Debugging(C++(GDB)调试)”中的一项。

如果选择了“Debug: C++ Launch”,则在“lauch.json”文件中输入以下代码:

{

  "version": "0.2.0",

  "configurations": [

    {

      "name": "C++ Launch",

      "type": "cppdbg",

      "request": "launch",

      "program": "${workspaceFolder}/hello.exe",

      "args": [],

      "stopAtEntry": true,

      "cwd": "${workspaceFolder}",

      "environment": [],

      "externalConsole": false

    }

  ]

}

如果选择了“C++(GDB)Debugging”,则在“tasks.json”和“launch.json”中输入以下代码:

“tasks.json”

{

  "version": "2.0.0",

  "tasks": [

    {

      "label": "C++ build active file",

      "type": "shell",

      "command": "C:\\MinGW\\bin\\g++.exe",

      "args": [

        "-g",

        "${file}",

        "-o",

        "${fileDirname}\\${fileBasenameNoExtension}.exe"

      ],

      "options": {

  "cwd": "${workspaceRoot}"

      },

      "problemMatcher": [

        "$gcc"

      ],

      "group":

        "isDefault": true

    }

  ]

}

“launch.json”

{

  "version": "0.2.0",

  "configurations": [

    {

      "name": "g++.exe build and debug active file",

      "type": "cppdbg",

      "request": "launch",

      "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",

      "args": [],

      "stopAtEntry": false,

      "cwd": "${fileDirname}",

      "environment": [],

      "externalConsole": true,

      "MIMode": "gdb",

      "miDebuggerPath": "C:\\MinGW\\bin\\gdb.exe",

      "setupCommands": [

          "description": "Enable function breakpoint"

      ]

    }

  ]

}

第五步:调试C++程序

在Visual Studio Code中,使用快捷键“F5”启动调试程序。如果C++程序顺利执行,则可以看到输出“Hello, World!”的结果。

总之,通过以上步骤运行C++程序是非常简单的,在Visual Studio Code中进行完美的C++编程!

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复