
C++ 入門指南 4.01
單元 2 - 如何編譯與執行

我們先看到以下
原始碼 (source code) 檔案就是我們寫程式 (program) 所用的 .cxx 檔案,原始碼檔案經過編譯器 (compiler) 編譯 (compile) 後就是可執行的程式檔案,然後在透過作業系統啟動程式執行。
我們提供的簡單範例的程式原始碼如下
// 引入標準程式庫中相關的輸入、輸出程式 #include <iostream> // std 為標準程式庫的命名空間 using namespace std; int main(void) { // 下面建立名稱為 m , string 型態的物件 // 小括弧為 string 的建構子,雙引號為字串字面常數 string m("There is no spoon."); // cout 用來輸出的物件, endl 為新行符號 '\n' cout << endl << m << endl << endl << endl; // 最後回傳 0 給作業系統 return 0; } /* 《程式語言教學誌》的範例程式 http://kaiching.org/ 檔名:demo.cxx 功能:示範簡單的 C++ 程式 作者:張凱慶 */
我們使用跨平台的編譯器 GCC 及 Geany ,於 Windows 、 Mac 或 Linux 的編譯結果都應一致。在 Windows 編譯,要先點擊組建按鈕,如下圖

UNIX-Like 作業系統如 Linux 、 Mac 等都已經預設安裝好 GCC , Windows 可安裝 MinGW 或 Cygwin ,兩者是 GCC 在 Windows 的安裝檔專案,詳細安裝與設定可參考在 Windows 11 中安裝 mingw-w64 及設定環境變數。
然後沒有出現錯誤的話,底下狀態列會顯示編譯成功結束,繼續點擊執行按鈕,如下圖

接下來就會跳出命令列視窗,顯示執行結果

相同目錄下會產生 demo.exe 檔案,也就是下圖中的應用程式檔案

上圖也可以看到, Geany 預設編譯出的程式名稱與原始碼名稱相同。
除了用 IDE 之外,也可以直接用命令列編譯執行本書的 C++ 的範例程式,例如以下用 Windows PowerShell 使用 g++ 指令編譯 demo.cxx ,預設編譯出的執行檔名為 a.exe

此程式沒有用到太多 C++ 的特性,僅利用 string 型態 (type) 的建構函數 (constructor) 建立字串 (string) 物件 (object) ,然後利用標準程式庫 (standard library) iostream 的 cout 物件輸出字串到螢幕上。
接下來,我們們會陸續探討 C++ 語言的諸多細節,先來看看基本內建型態 (primitive built-in type) 與物件吧!
中英文術語對照 | |
---|---|
編譯 | compile |
編譯器 | compiler |
建構函數 | constructor |
基本內建型態 | primitive built-in type |
程式 | program |
原始碼 | source code |
標準程式庫 | standard library |
字串 | string |
型態 | type |
重點整理 |
---|
1. GCC 為跨平台的編譯器,編譯 C++ 程式的指令為 g++ 。 |
2. C++ 程式編譯成功,會產生系統的執行檔。 |
3. 執行編譯完成的程式,於命令列輸入檔名即可。 |
問題與討論 |
---|
1. 編譯與直譯的差別在哪裡?編譯的程式語言相較直譯的程式語言有什麼優點及缺點? |
2. 於 Windows 編譯的執行檔可以拿到 Mac 執行嗎? |
練習 |
---|
1. 於命令列重新編譯 demo.cxx 。 |
2. 編譯「單元 1 」練習的 exercise0101.cxx ,並執行程式,比較與 demo.cxx 的編譯執行結果有何不同? |
3. 同上,改成編譯 exercise0102.cxx ,觀察能否編譯成功。 |
4. 同上,改成編譯 exercise0103.cxx 。 |
5. 同上,改成編譯 exercise0104.cxx 。 |
6. 同上,改成編譯 exercise0105.cxx 。 |
7. 同上,改成編譯 exercise0106.cxx 。 |
8. 同上,改成編譯 exercise0107.cxx 。 |
9. 同上,改成編譯 exercise0108.cxx 。 |
10. 同上,改成編譯 exercise0109.cxx 。 |
相關教學影片
