目錄
前期准備
安裝VScode
Visual Studio Code - Code Editing. Redefined
安裝 MinGW64
MinGW-w64 - for 32 and 64 bit Windows - Browse /mingw-w64/mingw-w64-release at SourceForge.net
這里本人推薦使用免安裝版本,直接配置環境變量即可,下載好以后解壓縮放到指定的盤符中
- 配置環境變量
例如本人的mingw64的解壓包放在D盤下,所以直接在path變量添加安裝包中的bin目錄的路徑即可
- 然后使用以下命令看是否配置成功
gcc -v
- 成功之后顯示如下
以上步驟可以參看Visual Studio Code (vscode) 配置 C / C++ 環境 - 步平凡 - 博客園 (cnblogs.com)
安裝C/C++插件
配置環境
創建一個簡單的C++文件
#include <iostream>
using namespace std;
int main(){
int a = 0;
a = 1;
a = 2;
int b = a;
cout << a + b << endl;
printf("hello world");
return 0;
}
創建c_cpp_properties.json文件
- 按快捷鍵Ctrl+Shift+P調出命令面板,輸入C/C++,選擇“Edit Configurations(UI)”進入配置
- 然后就會生成c_cpp_properties.json文件
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"compilerPath": "D:\\mingw64\\bin\\gcc.exe",
"cStandard": "gnu17",
"cppStandard": "gnu++14",
"intelliSenseMode": "windows-gcc-x64"
}
],
"version": 4
}
創建tasks.json文件
- 創建此文件來告訴VS Code如何構建(編譯)程序。該任務將調用g++編譯器基於源代碼創建可執行文件。
- 按快捷鍵Ctrl+Shift+P調出命令面板,輸入tasks,選擇Tasks:Configure Default Build Task
- 再選擇 C/C++: g++.exe build active file
- 此時就會生成一個tasks.json文件
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "compile", // 任務名稱,與launch.json的preLaunchTask相對應
"command": "D:\\mingw64\\bin\\g++.exe", // 編譯器的路徑
// 編譯c++文件使用g++.exe,c文件使用gcc.exe,此處編譯c++文件
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "D:\\mingw64\\bin"
},
"problemMatcher": [
"$gcc"
],
"group": "build"
}
],
"presentation": {
"panel": "new", //這里shared表示共享,改成new之后每個進程創建新的端口
}
}
創建launch.json
-
這個文件主要用來配置調試的相關信息
-
點擊菜單欄的Debug --> Start Debugging
-
選擇C++(GDB/LLDB)
-
此時就會產生launch.json的文件,上述圖中有
{
"version": "0.2.0",
"configurations": [
{
"name": "g(gdb) Launch", // 配置名稱,將會在啟動配置的下拉菜單中顯示
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false, //修改此項,讓其彈出終端
"internalConsoleOptions": "neverOpen", // 如果不設為neverOpen,調試時會跳到“調試控制台”選項卡
"MIMode": "gdb",
"miDebuggerPath": "D:\\mingw64\\bin\\gdb.exe",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "compile" //修改此項
// 調試會話開始前執行的任務,一般為編譯程序。與tasks.json的label相對應
}
]
}
- 這個時候就能夠對C++文件進行調試了,但是調試C文件是可能會報錯,這是因為在tasks.json文件中我配置的是c++的編譯器,如果要編譯C語言,在tasks.json文件中進行修改即可,修改的方法已在該文件中注釋,請自行瀏覽
參考文檔
感謝上述兩位大佬的博客,解決了本人的困惑
使用CodeRunner插件
這里推薦使用一款非常好用的vscode插件,這個插件支持支持了 Node.js, Python, C++, Java, PHP, Perl, Ruby, Go等超過40種的語言,可以不Debug直接運行代碼
以上就是全部內容,歡迎各位大佬斧正