# 安裝 MinGW (GCC/G++) C/CPP 編譯器 :::spoiler {state="open"} **目錄** [toc] ::: <br/> > 參考影片: [How to Install MinGW (GCC/G++) Compiler in Windows 11](https://youtu.be/-KayVZq1a58?si=ETIpGynsiDi_jyoT) ## MinGW 簡介 MinGW(Minimalist GNU for Windows) 一個歷史悠久的開源開發環境,提供 Windows 上的 GCC(GNU Compiler Collection),允許開發者使用 C、C++、Fortran 等語言進行開發。 - **輕量級**:相比於 Cygwin,MinGW 提供較少的 POSIX 兼容層,執行時不需額外模擬環境。 - **原生 Windows 編譯**:編譯的程式不依賴於 Cygwin 的 cygwin1.dll,樸實簡單沒有花俏。 - **支援多種 GCC 工具**:包括 ++gcc++、++g\+\+++、gdb、make 等。 <br> ## 1. GNU Compiler Collection (GCC) 下載 ([載點](https://sourceforge.net/projects/mingw/))  a. 點 Download 會下載一個 ++setup.exe++  b. 開啟執行檔來開始完整的 source 安裝 -  - Installation Directory (選擇安裝在你電腦上的位置:預設在C槽根目錄) -  - Process Done:點 `continue` -  - Installation Manager: Basic Setup 全打勾 (C/C++ 編譯器) -  - 左上角 Meue `Installation` -> Apply Changes -> 再點選 `Apply` -  - Applied Successfully (`Close` 安裝完成 可以關掉了) -  <br/> ## 2. 環境設置  如果你安裝在預設位置 那你會在 C 槽的根目錄 直接找到 `MinGW` 的 Folder a. MinGW 內容: -  b. 找到 `bin` Folder (Binary - 二進位執行檔) - `gcc.exe`:C 編譯器 - `g++.exe`:C++ 編譯器 c. 設定系統環境變數(Environment Variable) - 第一步就是直接複製 `bin` Folder 的路經 -  - 下一步利用 Windows 的搜尋開啟 `環境變數設置` (中文) -  - 開啟後點 `環境變數設定...` -  - 在 System variables 找到 `Path` 的選項 點進去 => -  - 把剛剛複製的路徑貼到最下面空白行: -  - 點選 OK 後這樣設置就完成了 <br/> ## 3. 測試本機編譯環境 - 先來檢查安裝版本 - 可以搜尋 cmd 來打開命令提示字元或是 `win 鍵+R` 輸入 cmd -  - 打上: ```ssh= gcc --version g++ --version ``` -  -  - 若顯示出版本資訊 ==這樣就確認了都安裝成功了== <br/> ## 4. 使用 MinGW 編譯 C/CPP 程式 1. 編譯 C 程式 - 建立 `hello.c`: ```c[] #include <stdio.h> int main() { printf("Hello, MinGW!\n"); return 0; } ``` - 編譯並執行: ```ssh= gcc hello.c -o hello.exe hello.exe ``` 2. 編譯 C++ 程式 - 建立 `hello.cpp`: ```c[] #include <iostream> using namespace std; int main() { cout << "Hello, MinGW!" << endl; return 0; } ``` - 編譯並執行: ```ssh= g++ hello.cpp -o hello.exe hello.exe ``` <br/> ## 5. 常見錯誤與解決方案 | 錯誤訊息 | 可能原因 | 解決方案 | |-|-|-| | `gcc: command not found` | 環境變數未設置正確 | 確保 Path 包含 `C:\mingw-w64\mingw64\bin` | | `cannot find -lstdc++` | 標準 C++ 庫遺失 | 使用 `-static-libgcc -static-libstdc++` | | `undefined reference to 'WinMain'` | C++ `main()` 格式錯誤 | 確保 `main()` 定義為 `int main()` | | `No rule to make target` | Makefile 語法錯誤 | 確保 Makefile 使用 `Tab` 而非 `空格` | <br/> :::spoiler Relevant Sources - 透過 Makefile 自動化編譯流程,提高開發效率:[Makefile 教學](https://hackmd.io/@sysprog/SySTMXPvl) - [YouTube - 編譯與鏈結](https://youtu.be/1IIUvVrCSF0?t=293) :::
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.