C++編譯原理簡介
一個完整的C++程序開發(fā)大致經(jīng)歷以下幾個步驟:
- coding: 使用編輯器編寫程序,這個文件就是程序源代碼。
- compile: 編譯源代碼,這意味著將程序源代碼翻譯成機器語言,得到目標(biāo)代碼(object code,以o或obj作為文件后綴),如果有語法錯誤,則會編譯失敗。
- link: 將目標(biāo)代碼、庫代碼和啟動代碼統(tǒng)一在一起。
-
build:compile+link+生成exe可執(zhí)行程序幾個步驟合在一起,就成為構(gòu)建(build)。
已有環(huán)境:
- Windows 10系統(tǒng)
- Visual Studio Code
Step1:安裝編譯器
大多數(shù)Linux發(fā)行版與MacOS系統(tǒng)都自帶C++編譯器,而Windows則通常沒有。在命令行輸入命令檢查是否有g(shù)cc編譯器:
g++ --version
檢查是否有clang編譯器:
clang --version
命令行顯示:

則說明編譯器不存在。
首先我們在windows安裝MYSYS2:
- MSYS2是一組工具和庫,為用戶提供易于使用的環(huán)境,用于構(gòu)建、安裝和運行本機 Windows 軟件。此工具包含mintty命令行終端,以及bash,以及git和subversion等版本控制工具,以及tar和awk等工具。MSYS2 為 GCC、mingw-w64、CPython、CMake、Meson、OpenSSL、FFmpeg、Rust、Ruby 等提供最新的原生構(gòu)建。它提供了一個名為Pacman的軟件包管理系統(tǒng)。
安裝完成后,需要勾選Run MSYS 64bit now:

然后在命令行輸入pacman -Syu以更新軟件包:
$ pacman -Syu
:: Synchronizing package databases...
mingw32 805.0 KiB
mingw32.sig 438.0 B
mingw64 807.9 KiB
mingw64.sig 438.0 B
msys 289.3 KiB
msys.sig 438.0 B
:: Starting core system upgrade...
warning: terminate other MSYS2 programs before proceeding
resolving dependencies...
looking for conflicting packages...
Packages (6) bash-5.1.004-1 filesystem-2021.01-1
mintty-1~3.4.4-1 msys2-runtime-3.1.7-4
pacman-5.2.2-9 pacman-mirrors-20201208-1
Total Download Size: 11.05 MiB
Total Installed Size: 53.92 MiB
Net Upgrade Size: -1.24 MiB
:: Proceed with installation? [Y/n]
:: Retrieving packages...
bash-5.1.004-1-x86_64 2.3 MiB
filesystem-2021.01-1-any 33.2 KiB
mintty-1~3.4.4-1-x86_64 767.2 KiB
msys2-runtime-3.1.7-4-x86_64 2.6 MiB
pacman-mirrors-20201208-1-any 3.8 KiB
pacman-5.2.2-9-x86_64 5.4 MiB
(6/6) checking keys in keyring 100%
(6/6) checking package integrity 100%
(6/6) loading package files 100%
(6/6) checking for file conflicts 100%
(6/6) checking available disk space 100%
:: Processing package changes...
(1/6) upgrading bash 100%
(2/6) upgrading filesystem 100%
(3/6) upgrading mintty 100%
(4/6) upgrading msys2-runtime 100%
(5/6) upgrading pacman-mirrors 100%
(6/6) upgrading pacman 100%
:: To complete this update all MSYS2 processes including this terminal will be closed. Confirm to proceed [Y/n]
完成這個步驟后會關(guān)閉命令行窗口。我們需要再次在開始菜單搜索MSYS2啟動命令行,輸入pacman -Su更新剩下的包(這些步驟是官方教程給的,我也想不懂為啥是這樣的):
$ pacman -Su
:: Starting core system upgrade...
there is nothing to do
:: Starting full system upgrade...
resolving dependencies...
looking for conflicting packages...
Packages (20) base-2020.12-1 bsdtar-3.5.0-1
[... more packages listed ...]
Total Download Size: 12.82 MiB
Total Installed Size: 44.25 MiB
Net Upgrade Size: 3.01 MiB
:: Proceed with installation? [Y/n]
[... downloading and installation continues ...]
接下來輸入pacman -S --needed base-devel mingw-w64-x86_64-toolchain來安裝mingw-w64 gcc工具集。
Step2:GCC加入環(huán)境變量
如下圖,在系統(tǒng)變量->Path中添加C:\msys64\mingw63\bin:

啟動或者重啟Powershell,輸入
gcc --version,顯示了gcc版本,則說明編譯器安裝成功。

Step3:vscode中構(gòu)建C++程序
首先在vscode擴展商店里安裝C/C++以及C/C++ Extension Pack,再安裝一個code runner:


然后在工程根目錄下編寫C++程序,以編寫一個計算階乘的程序為例:
#include<iostream>
#include <stdlib.h>
using namespace std;
long long fact(long long n) {
if (n < 0) return -1;
if (n == 0) return 1;
return n * fact(n - 1);
}
int main() {
long long n;
cout << "Please input number: ";
cin >> n;
long long res = fact(n);
cout << "Factorial of " << n << " is " << res << endl;
system("pause...");
return 0;
}
如何build寫好的程序:點擊終端/Terminal->運行生成任務(wù)/Run build task->選擇C/C++: g++.exe生成活動文件


此時在左側(cè)資源管理器顯示了構(gòu)建的exe文件:

快捷鍵
ctrl+~在vscode調(diào)出powershell,輸入./fact,就可以啟動程序了:
c_cpp_properties.json配置文件
VSCode C++配置文件主要包括./.vscode目錄下的:
- c_cpp_properties.json:c/c++相關(guān)的基礎(chǔ)配置
- tasks.json:構(gòu)建任務(wù)的配置
- launch.json:debug配置
點擊ctrl+shift+p調(diào)出命令面板,然后輸入c/c++,選擇edit configurations:

此時工程目錄就會自動新建.vscode文件夾,編輯里面的c_cpp_properties.json:
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/include"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE",
"MAX_NUM=100"
],
"windowsSdkVersion": "10.0.19041.0",
"compilerPath": "C:\\msys64\\mingw64\\bin\\g++.exe",
"cStandard": "c11",
"cppStandard": "c++17",
"intelliSenseMode": "gcc-x64"
}
],
"version": 4
}
configurations下面包含了多組配置對象,version官方建議不要修改此字段,它主要用于版本跟蹤。configurations下面的配置有:
- includePath:引入頭文件的路徑。我通常會將需要引入的頭文件復(fù)制到工程目錄的include子路徑下,includePath寫
"${workspaceFolder}/include"。 - compilerPath:編譯器路徑,填寫剛才安裝的編譯器路徑
C:\msys64\mingw64\bin\g++.exe - intelliSenseMode:智能感知編譯器版本,不同系統(tǒng)有不同的默認(rèn)值(MSVC,gcc,clang)。我填寫
gcc-x64 - defines:IntelliSense引擎在解析文件時使用的預(yù)處理器定義列表
tasks.json配置文件
tasks.json將會告訴vscode如何構(gòu)建你的c++程序。點擊終端->配置默認(rèn)生成任務(wù),此時.vscode目錄會新建一個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"
}
]
}
tasks內(nèi)包含多組任務(wù)配置對象,每個對象的配置如下:
- label:任務(wù)名稱
- command制定用什么編譯器構(gòu)建,可以寫編譯器的絕對路徑;如果編譯器添加到了系統(tǒng)變量,也可以直接寫g++;
- args:命令行中給g++傳入的參數(shù)
launch.json配置文件
此配置文件主要用于debugger的配置。點擊運行->添加配置->C++ (GDB/LLDB),選擇編譯器,此時.vscode目錄下會自動生成launch.json配置文件:
{
// 使用 IntelliSense 了解相關(guān)屬性。
// 懸停以查看現(xiàn)有屬性的描述。
// 欲了解更多信息,請訪問: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "g++ - 生成和調(diào)試活動文件",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}\\${fileBasenameNoExtension}.exe",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"miDebuggerPath": "gdb.exe",
"setupCommands": [
{
"description": "為 gdb 啟用整齊打印",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: g++.exe 生成活動文件"
}
]
}
在此我直接使用系統(tǒng)默認(rèn)的配置,更詳細(xì)的配置參考下方reference的debugging。然后給程序打好斷點,點擊左側(cè)活動欄的運行和調(diào)試,點擊g++ 生成和調(diào)試活動文件,就可以debug了:

Reference
C/C++ for Visual Studio Code
MSYS2 installation guide
c_cpp_properties.json reference
Debugging
