Mac 環境建置、測試
以下以 macOS 內建的 **Terminal** 與 **Clang** 為例,建立基本的 C 語言開發環境。
## 1. 安裝 C 編譯器
macOS 通常使用 Apple 提供的 **Clang** 編譯器。開啟「終端機」:
1. 按下 `Command + Space`
2. 輸入「Terminal」或「終端機」
3. 開啟後執行:
```bash
xcode-select --install
```
系統會顯示安裝視窗,按下「Install」即可。
安裝完成後,可以確認 Clang 是否可用:
```bash
clang --version
```
若看到版本資訊,例如:
```text
Apple clang version ...
```
就表示安裝成功。
> 不一定需要安裝完整的 Xcode。若只是學習 C,安裝 Command Line Tools 已經足夠。
---
## 2. 準備程式碼編輯器
可以使用以下任一種方式編輯 C 程式:
- macOS 內建的 `nano`
- Visual Studio Code
- Xcode
- 其他文字編輯器
初學者可以先使用 Terminal 內建的 `nano`,不需要額外安裝軟體。
先建立一個工作資料夾:
```bash
mkdir -p ~/c-projects/hello
cd ~/c-projects/hello
```
確認目前所在位置:
```bash
pwd
```
---
## 3. 建立 Hello World 程式
使用 `nano` 建立 `hello.c`:
```bash
nano hello.c
```
輸入以下程式:
```c
#include <stdio.h>
int main(void)
{
printf("Hello, World!\n");
return 0;
}
```
說明:
- `#include <stdio.h>`:引入標準輸入輸出函式庫
- `main`:C 程式的執行入口
- `printf`:在螢幕上輸出文字
- `\n`:換行
- `return 0`:表示程式正常結束
在 `nano` 中:
1. 按 `Control + O` 儲存
2. 按 `Enter` 確認檔名
3. 按 `Control + X` 離開
確認檔案存在:
```bash
ls
```
應該會看到:
```text
hello.c
```
---
## 4. 編譯 C 程式
執行以下指令:
```bash
clang -Wall -Wextra -std=c17 hello.c -o hello
```
各參數用途如下:
- `clang`:C 編譯器
- `-Wall`:顯示常見警告
- `-Wextra`:顯示額外警告
- `-std=c17`:使用 C17 標準
- `hello.c`:原始程式檔
- `-o hello`:輸出名為 `hello` 的執行檔
如果編譯成功,通常不會顯示任何訊息,並會產生一個名為 `hello` 的執行檔。
可以用以下指令確認:
```bash
ls
```
應該會看到:
```text
hello
hello.c
```
---
## 5. 執行程式
在 macOS 或 Linux 中,執行目前資料夾裡的程式需要加上 `./`:
```bash
./hello
```
輸出結果:
```text
Hello, World!
```
---
## 6. 完整操作流程
之後建立一般 C 程式時,可以依照以下流程:
```bash
mkdir -p ~/c-projects/hello
cd ~/c-projects/hello
nano hello.c
clang -Wall -Wextra -std=c17 hello.c -o hello
./hello
```
---
## 7. 常見問題
### 找不到 `clang`
如果執行:
```bash
clang --version
```
出現找不到指令,請重新安裝:
```bash
xcode-select --install
```
如果仍然有問題,可以確認開發工具路徑:
```bash
xcode-select -p
```
必要時切換到正確路徑:
```bash
sudo xcode-select --switch /Library/Developer/CommandLineTools
```
---
### 編譯時出現警告
警告不一定會阻止程式執行,但通常代表程式可能有潛在問題。建議在學習階段保留:
```bash
-Wall -Wextra
```
例如,變數宣告但沒有使用,Clang 可能會顯示警告。
---
### `gcc` 和 `clang` 的差異
macOS 上輸入:
```bash
gcc
```
通常實際上也是 Apple 提供的 Clang。學習 C 時直接使用:
```bash
clang
```
即可。
---
## 8. 使用 Visual Studio Code(可選)
如果希望使用圖形化編輯器,可以:
1. 安裝 Visual Studio Code
2. 安裝 C/C++ 擴充功能
3. 使用 VS Code 開啟 `hello.c`
4. 在 Terminal 中執行編譯和執行指令:
```bash
clang -Wall -Wextra -std=c17 hello.c -o hello
./hello
```
如此便完成了 macOS 上最基本的 C 語言開發環境與第一個 Hello World 程式。
相關學習地圖、教學課程
C 語言,系統程式