語法書 / AA 競程語法書 上冊 / 第一單元 / 編譯錯誤訊息的解讀

1.9 編譯錯誤訊息的解讀

當編譯失敗時,編譯器會印出「編譯錯誤(Compilation Error, CE)」訊息。讀懂這些訊息,能快速找出問題。

編譯器的錯誤訊息一般格式:

[檔案名]:[行號]:[列號]: error: [錯誤訊息]

常見編譯錯誤及解決方式

✘ 錯誤 1:忘記分號

int a = 5        // 少了分號
cout << a << endl;

錯誤訊息:

add.cpp:4:10: error: expected ';' before 'cout'

解決:在 int a = 5 那行補上分號:int a = 5;

✘ 錯誤 2:'某個名字' was not declared in this scope

這是最常見的編譯錯誤,意思是「你用了一個編譯器不認得的名字」。同一句訊息,常見有三種原因:

(a) 用了 coutcin,卻沒寫 #include <iostream>using namespace std;

int main() {
    cout << "Hello" << endl;   // 開頭少了 #include 和 using namespace std
    return 0;
}

error: 'cout' was not declared in this scope 解決:補上開頭兩行 #include <iostream>using namespace std;

(b) 用了某個變數,卻忘了先宣告它

int main() {
    cin >> a;   // a 沒有宣告
    return 0;
}

error: 'a' was not declared in this scope 解決:使用前先宣告,例如 int a;

(c) 用了某個工具(函式),卻沒 #include 它需要的那一行(這些函式之後才會用到,這裡先有個印象就好)

int main() {
    double x = sqrt(2.0);   // 用了 sqrt(平方根),卻沒 #include <cmath>
    return 0;
}

error: 'sqrt' was not declared in this scope 解決:補上那個工具需要的 #include,例如算平方根的 sqrt#include <cmath>

看到 ... was not declared in this scope,就照這三點檢查:名字打錯了嗎?該宣告的變數宣告了嗎?該 #include 的加了嗎?

✘ 錯誤 3:型態不符(型態錯誤)

int a = "abc";   // 想把一段文字塞進「整數」變數

錯誤訊息:

add.cpp:3:9: error: invalid conversion from 'const char*' to 'int'

解決:型態要對得上——int 變數只能放整數,不能直接塞文字。

如何讀錯誤訊息

  1. 看行號:錯誤在第幾行,定位到那一行
  2. 看列號:在那一行的第幾個字元(有時不精確,但能縮小範圍)
  3. 看訊息:理解編譯器在說什麼
  4. 修改並重新編譯:改完一個錯誤後,重新編譯,可能會發現新的錯誤

動手試試看

  1. 故意在程式裡製造上面講過的幾種錯誤(漏分號、漏 #includeusing namespace std;、用了沒宣告的變數、型態放錯…),看看編譯器各自怎麼報
  2. 試著只看錯誤訊息,自己找出問題並修好