1. 程式人生 > 其它 ># VScode C/C++ 環境配置教程 (GCC)

# VScode C/C++ 環境配置教程 (GCC)

更好的觀看體驗,歡迎移步 WuJune’s Blog

VScode C/C++ 環境配置教程 (GCC)

簡潔版

  • 安裝 MSYS2
  • 在 MSYS2 裡面 pacman -S mingw-w64-x86_64-toolchain 安裝 MinGW-64
  • MinGW 環境變數配置(可選項)
  • VScode 安裝 C/C++ Extension Pack
  • 在原始碼資料夾的 .vscode 資料夾中配置 tasks.jsonlaunch.json

編譯器安裝

對於 Windows 下的 GCC 安裝目前有多種解決方案,如 MinGW專案,MinGW-64 專案,Cygwin 專案, MSYS2 專案等,其中 MSYS2 是一個較為活躍的專案,他提供了一個 Linux Like shell 環境,以及 Pacman 包管理系統,因此在使用管理上更為科學。在後續使用中,我們也將通過 MSYS2 的包管理器來安裝 MinGW-64,而 MinGW-64 中包含了 GCC。

MSYS2 安裝

MSYS2 下載安裝包,當前版本為 msys2-x86_64-20220319.exe,下載之後直接開啟進行安裝

一路上基本不需要進行配置,按照軟體指示的進行下一步即可

需要注意一下的只有軟體的安裝路徑,後續我們配置命令列的環境變數需要用到

預設的安裝位置為 C:\msys64

這一步需要耐心等待好幾分鐘

安裝完後立即執行即可

開啟之後是這樣的一個 Shell 環境(打碼處是你的使用者名稱@主機名)

MSYS2 映象配置

MSYS2 安裝軟體時是從 Pacman 包管理器的庫中下載的,它的原始伺服器在國外,因此我們需要為包管理器切換到國內的庫映象源

這裡我們選擇清華源,清華 MSYS2 源

的說明如下:

編輯 /etc/pacman.d/mirrorlist.mingw32 ,在檔案開頭新增:

Server = https://mirrors.tuna.tsinghua.edu.cn/msys2/mingw/i686

編輯 /etc/pacman.d/mirrorlist.mingw64 ,在檔案開頭新增:

Server = https://mirrors.tuna.tsinghua.edu.cn/msys2/mingw/x86_64

編輯 /etc/pacman.d/mirrorlist.ucrt64 ,在檔案開頭新增:

Server = https://mirrors.tuna.tsinghua.edu.cn/msys2/mingw/ucrt64

編輯 /etc/pacman.d/mirrorlist.clang64 ,在檔案開頭新增:

Server = https://mirrors.tuna.tsinghua.edu.cn/msys2/mingw/clang64

編輯 /etc/pacman.d/mirrorlist.msys ,在檔案開頭新增:

Server = https://mirrors.tuna.tsinghua.edu.cn/msys2/msys/$arch

然後執行 pacman -Sy 重新整理軟體包資料即可。

注: 本Help參考自USTC映象

我們只需要安裝 MinGW-64 相關庫、包,因此這裡我們只需配置 MinGW-64 的映象檔案,讀者有需求的後續自行配置即可

配置步驟:

注,這部分的命令列均在 MSYS2 中執行

  • 先對原檔案進行備份,良好的使用習慣
cp /etc/pacman.d/mirrorlist.mingw64 /etc/pacman.d/mirrorlist.mingw64.bkp
  • 編輯配置檔案
sed -i '1iServer = https://mirrors.tuna.tsinghua.edu.cn/msys2/mingw/x86_64' /etc/pacman.d/mirrorlist.mingw64
  • 檢視編輯結果
cat /etc/pacman.d/mirrorlist.mingw64 

上一步檢視的輸出如下,可以看到清華源的已經成功新增到配置檔案的第一行中

Server = https://mirrors.tuna.tsinghua.edu.cn/msys2/mingw/x86_64
 See https://www.msys2.org/dev/mirrors

# Primary
Server = https://mirror.msys2.org/mingw/x86_64/
Server = https://repo.msys2.org/mingw/x86_64/

# Tier 1
Server = https://mirror.umd.edu/msys2/mingw/x86_64/
Server = https://mirror.yandex.ru/mirrors/msys2/mingw/x86_64/
Server = https://download.nus.edu.sg/mirror/msys2/mingw/x86_64/
Server = https://ftp.acc.umu.se/mirror/msys2.org/mingw/x86_64/
Server = https://ftp.nluug.nl/pub/os/windows/msys2/builds/mingw/x86_64/
Server = https://ftp.osuosl.org/pub/msys2/mingw/x86_64/
Server = https://mirror.internet.asn.au/pub/msys2/mingw/x86_64/
Server = https://mirror.selfnet.de/msys2/mingw/x86_64/
Server = https://mirror.ufro.cl/msys2/mingw/x86_64/
Server = https://mirrors.dotsrc.org/msys2/mingw/x86_64/
Server = https://mirrors.bfsu.edu.cn/msys2/mingw/x86_64/
Server = https://mirrors.tuna.tsinghua.edu.cn/msys2/mingw/x86_64/
Server = https://mirrors.ustc.edu.cn/msys2/mingw/x86_64/
Server = https://mirror.nju.edu.cn/msys2/mingw/x86_64/
Server = https://repo.extreme-ix.org/msys2/mingw/x86_64/
Server = https://mirrors.hit.edu.cn/msys2/mingw/x86_64/

# Tier 2
Server = https://mirror.clarkson.edu/msys2/mingw/x86_64/
Server = https://fastmirror.pp.ua/msys2/mingw/x86_64/
Server = https://ftp.cc.uoc.gr/mirrors/msys2/mingw/x86_64/
Server = https://mirror.jmu.edu/pub/msys2/mingw/x86_64/
Server = https://mirrors.piconets.webwerks.in/msys2-mirror/mingw/x86_64/
Server = https://quantum-mirror.hu/mirrors/pub/msys2/mingw/x86_64/
Server = https://www2.futureware.at/~nickoe/msys2-mirror/mingw/x86_64/
Server = https://mirrors.sjtug.sjtu.edu.cn/msys2/mingw/x86_64/
Server = https://mirrors.bit.edu.cn/msys2/mingw/x86_64/
Server = https://repo.casualgamer.ca/mingw/x86_64/
Server = https://mirrors.aliyun.com/msys2/mingw/x86_64/
Server = https://mirror.iscas.ac.cn/msys2/mingw/x86_64/

  • 重新整理包管理器快取
pacman -Sy 

安裝 MinGW-64 工具鏈(GCC)

Mingw-w64 includes a port of the GNU Compiler Collection (GCC), GNU Binutils for Windows (assembler, linker, archive manager), a set of freely distributable Windows specific header files and static import libraries which enable the use of the Windows API, a Windows native build of the GNU Project's GNU Debugger, and miscellaneous utilities.

來源:維基百科

Mingw-w64包括GNU Compiler Collection (GCC)的埠,GNU Binutils Windows(彙編器、聯結器、歸檔管理器),一組釋出的Windows特定標頭檔案和靜態匯入庫啟用Windows API的使用,一個Windows本地構建GNU專案的GNU偵錯程式,和各種各樣的實用程式。

簡單來說,MinGW-w64 提供了包括 GCC 編譯器在內的一系列 GNU 工具,在 Windows 上提供 GNU 支援

注:以下命令依舊在 MSYS2 中執行

  • 安裝 MinGW-64
pacman -S mingw-w64-x86_64-toolchain

預設會安裝以下一系列包,連續回車確認即可

下載中 ,可以看到配置清華源之後下載速度還是很快的

安裝中,需要耐心等待幾分鐘

安裝完畢後,之前我們的 MSYS2 預設是安裝在 C:\msys64 ,因此對應的 MinGW64 在 C:\msys64\mingw64

此時我們的 C:\msys64\mingw64\bin 路徑下應該出現了很多的 *.exe ,其中就包括

  • gcc.exe
  • g++.exe
  • gdb.exe

這三個可執行檔案向用戶提供了主要的編譯、Debug功能支援,其中 gcc.exe 是整個gcc 的入口,它也可以編譯 .cpp ,但為了避免不必要的麻煩,我們還是顯式使用 g++.exe

GCC 環境變數配置(可選、建議)

在通過 VScode 使用 GCC 時,編譯器路徑都配置在 .vscode 裡面的配置檔案裡面,因此環境變數並不是必須的

但有時我們也需要通過終端手動進行編譯,因此筆者建議還是配置一下環境變數

在系統變數的 Path 中新增 C:\msys64\mingw64\bin ,這能讓我們在 cmdpowershell 中直接使用 g++ xxx.cpp 等命令

配置過程如下:

Win + S 搜尋 編輯系統環境變數

選擇 環境變數

選擇中編輯 系統變數 中的 Path

新建一個行後輸入 C:\msys64\mingw64\bin

然後 確定 -> 確定 -> 確定 關閉視窗

此時開啟一個新的 cmd 或者 powershell 終端(重新開啟的終端裡面或者電腦重啟之後環境變數才會生效)

  • 執行測試命令
gcc -v

如果配置成功的話此時會有如下輸出,說明此時 gcc 已經在我們的電腦裡配置好了

Using built-in specs.
COLLECT_GCC=C:\msys64\mingw64\bin\gcc.exe
COLLECT_LTO_WRAPPER=C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/11.2.0/lto-wrapper.exe
Target: x86_64-w64-mingw32
Configured with: ../gcc-11.2.0/configure --prefix=/mingw64 --with-local-prefix=/mingw64/local --build=x86_64-w64-mingw32 --host=x86_64-w64-mingw32 --target=x86_64-w64-mingw32 --with-native-system-header-dir=/mingw64/include --libexecdir=/mingw64/lib --enable-bootstrap --enable-checking=release --with-arch=x86-64 --with-tune=generic --enable-languages=c,lto,c++,fortran,ada,objc,obj-c++,jit --enable-shared --enable-static --enable-libatomic --enable-threads=posix --enable-graphite --enable-fully-dynamic-string --enable-libstdcxx-filesystem-ts --enable-libstdcxx-time --disable-libstdcxx-pch --disable-libstdcxx-debug --enable-lto --enable-libgomp --disable-multilib --disable-rpath --disable-win32-registry --disable-nls --disable-werror --disable-symvers --with-libiconv --with-system-zlib --with-gmp=/mingw64 --with-mpfr=/mingw64 --with-mpc=/mingw64 --with-isl=/mingw64 --with-pkgversion='Rev10, Built by MSYS2 project' --with-bugurl=https://github.com/msys2/MINGW-packages/issues --with-gnu-as --with-gnu-ld --with-boot-ldflags='-pipe -Wl,--disable-dynamicbase -static-libstdc++ -static-libgcc' LDFLAGS_FOR_TARGET=-pipe --enable-linker-plugin-flags='LDFLAGS=-static-libstdc++\ -static-libgcc\ -pipe\ -Wl,--stack,12582912'
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 11.2.0 (Rev10, Built by MSYS2 project)

VScode 配置

新建一個資料夾用來寫程式碼

在 VScode 中開啟這個資料夾

這裡我們用 C:\cpp_test 資料夾來做演示

安裝 C/C++ 外掛

開啟 VScode 後 安裝 C/C++ Extension Pack 外掛,裡面主要包含了 C/C++ 用來做編輯器中 C++ 的語法高亮提示、補全和包括 Cmake 和一些其它開發工具,對於新手來說筆者覺得不需要太早接觸 Cmake,簡單進行一些熟悉練習之後再轉向 Cmake 即可

通過外掛自動配置,直接執行

新建一個用於測試的原始檔 test.cpp

原始檔內容如下

include <iostream>

int main()
{
    std::cout << "Hello World!" << std::endl;
    return 0;
}

此時我們可以看到, VScode 右上角提供了 DebugRunRun File 三個選項,可以看到 C/C++ 外掛已經提供了比較良好的支援

如果之前的 MinGW 已經配置好了的話,這裡我們應該已經可以直接通過這三個選項來 DebugRun 了,不必要進行額外配置

Run Code

直接選擇 Run Code

輸出結果如下

可以看到,VScode 呼叫了 g++ 命令來編譯我們的 test.cpp 原始碼,並輸出 test.exe,然後運行了 test.exe

cd "c:\cpp_test\" && g++ test.cpp -o test && "c:\cpp_test\"test

執行輸出結果

Hello World!

Debug C/C++ File

當我們選擇 Debug

會彈窗讓我們配置檔案,三個選項分別用於生成 g++.execpp.execl.exe 對應的配置模板

前兩項都對應 gcc ,而 cl.exe 則是微軟的編譯器,這裡我們選擇g++.exe

選中 VScode 就會自動在當前目錄的 .vscode 目錄下的 task.json 新生成用於 Debug 的一個 task,生成之後就會自動繼續 Debug,也就是執行這個 task,執行結果應該如下圖

我們可以看到有兩個 TERMINAL

其中第一個 terminal 是 task 執行的輸出結果

我們可以開啟 .vscode/tasks.json 檢視這個 task 的配置

可以看到這個 task C/C++: g++.exe 生成活動檔案 用於編譯帶 debug 資訊的可執行檔案 test.exe

配置的具體內容如下

{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++.exe 生成活動檔案",
            "command": "C:\\msys64\\mingw64\\bin\\g++.exe",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "偵錯程式生成的任務。"
        }
    ],
    "version": "2.0.0"
}

第二個 terminal 則是通過 gdb.exe 來讓 VScode 對 test.exe 進行 debug,執行結果如下

由於我們並沒有打斷點,因此預期的結果應該是程式順利執行輸出結果 Hello World! 並結束執行

第二個 terminal 部分的功能配置本來應該是在 .vscode/launch.json 中配置,筆者猜測這裡是整合在了 C/C++ 外掛中,減輕了使用者的配置負擔

添加個變數用於觀察 int a = 1;

我們在第7行打個斷點再進行 Debug 試試

此時 VScode 會自動跳轉到 Debug 介面,可以看到區域性變數等資訊都在右側欄,關於 Debug 的更多使用這裡就不再進一步探討

Run C/C++ File

當我們選擇 Run C/C++ File 時可以看到和沒打斷點之前的輸出結果差不多,而手動打斷點之後 Run C/C++ File 也不會

也就是是 Run C/C++ File 應該就是 Run Without Debugging

手動配置(可選)

注:通過外掛自動配置和手動配置中選一個就可以了(也可以都進行配置,它們並不衝突

這裡再提供手動配置來配置 Debug 配置的簡單說明(對這部分有興趣的人俺相信你可以自行探索細節

和自動配置一樣,新建一個資料夾用來寫程式碼

在 VScode 中開啟這個資料夾

這裡我們用 C:\cpp_test 資料夾來做演示

新建一個用來演示的原始碼 test.cpp

編譯配置

從 VScode 的頂欄選單中選中 Terminal > Configure Default Build Task

從彈出的選項中選擇 g++.exe 生成活動檔案

然後 VScode 就會自動在當前資料夾建立 .vscode.vscode\tasks.json

其中,tasks.json 如下

{
	"version": "2.0.0",
	"tasks": [
		{
			"type": "cppbuild",
			"label": "C/C++: g++.exe 生成活動檔案",
			"command": "C:\\msys64\\mingw64\\bin\\g++.exe",
			"args": [
				"-fdiagnostics-color=always",
				"-g",
				"${file}",
				"-o",
				"${fileDirname}\\${fileBasenameNoExtension}.exe"
			],
			"options": {
				"cwd": "${fileDirname}"
			},
			"problemMatcher": [
				"$gcc"
			],
			"group": {
				"kind": "build",
				"isDefault": true
			},
			"detail": "編譯器: C:\\msys64\\mingw64\\bin\\g++.exe"
		}
	]
}

當配置生成之後我們就可以通過 Terminal > Configure Default Build Task 來進行編譯,編譯輸出如下

可以看到 test.exe 已經生成

  • 接下來就可以在 VScode 整合的終端中執行 test.exe
./test.exe

Debug 配置

從 VScode 的頂欄選單中選中 Run > Add Configuration

從彈出的選項中選擇 C++ (GDB/LLDB)

按官方文件 Get Started with C++ and Mingw-w64 in Visual Studio Code,在選擇 C++ (GDB/LLDB) 後這裡應該會跳出模板讓我們選擇然後自動生成,但俺在實踐的時候發現並沒有,那就手動配置吧

最開始你的 launch.json 應該看起來是這樣的

點選右下角 Add Configurations,選擇 (gdb) 啟動

現在你的 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": "(gdb) 啟動",
            "type": "cppdbg",
            "request": "launch",
            "program": "輸入程式名稱,例如 ${workspaceFolder}/a.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "/path/to/gdb",
            "setupCommands": [
                {
                    "description": "為 gdb 啟用整齊列印",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                },
                {
                    "description":  "將反彙編風格設定為 Intel",
                    "text": "-gdb-set disassembly-flavor intel",
                    "ignoreFailures": true
                }
            ]
        }
    ]
}

這裡我們需要修改的有

  • "program" 修改到與 tasks.json 中的 args 匹配,如果你用的是預設配置的話那就應該是 "${fileDirname}\\${fileBasenameNoExtension}.exe"
  • "miDebuggerPath" 修改到和你的 gdb.exe 全域性路徑匹配,如果你的 MSYS2 和 MinGW64都是採用預設安裝路徑的話那就應該是C:\\msys64\\mingw64\\bin\\gdb.exe
  • 新增 "preLaunchTask" 項來在每次 Debug 前重新編譯,這裡應該和 tasks.json 裡面匹配,如果你用的是預設配置的話那就應該是 C/C++: g++.exe 生成活動檔案

修改完後你的 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": "(gdb) 啟動",
            "type": "cppdbg",
            "request": "launch",
            "program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${fileDirname}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "C:\\msys64\\mingw64\\bin\\gdb.exe",
            "setupCommands": [
                {
                    "description": "為 gdb 啟用整齊列印",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                },
                {
                    "description":  "將反彙編風格設定為 Intel",
                    "text": "-gdb-set disassembly-flavor intel",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "C/C++: g++.exe 生成活動檔案"
        }
    ]
}

配置完成後就可以通過頂欄選單 Run > Start Debugging 來進行 Debug 了

總結

本文更多是對官方文件的 Get Started with C++ and Mingw-w64 in Visual Studio Code 實踐、翻譯、補充,慚愧,建議有興趣的讀者可以去讀一下原文件

畫餅

後續可能出一篇 VScode + MSVC(VisualStudio C++)的文章

參考文獻

[1] Get Started with C++ and Mingw-w64 in Visual Studio Code