1.9 編譯錯誤訊息的解讀
編譯失敗(Compile Error,CE)時編譯器印出的訊息長什麼樣、怎麼分段,1.4 已經看過(檔名:行號:欄號: error: 說明,欄號就是那一行的第幾個字;先看行號);訊息裡的 numeric constant、'operator<<' 這些詞是 1.5 的 token 類型。這一節整理初學者最常撞到的幾種錯誤,以及各自怎麼修。
¶常見編譯錯誤及解決方式
¶✘ 錯誤 1:忘記分號
#include <iostream>
using namespace std;
int main() {
int a = 5 // 少了分號
cout << a << endl;
return 0;
}
錯誤訊息:
add.cpp:6:5: error: expected ',' or ';' before 'cout'
解決:在第 5 行 int a = 5 補上分號:int a = 5;。注意訊息報的是第 6 行(cout 那一行)——編譯器是讀到 cout 才發現前面沒收尾。
少分號時,先看行號後面的欄號(那一行的第幾個字):
- 指在那一行的最後面:就是這一行少了分號。拿 1.3 的 A+B 來試,
cin >> a >> b少分號時訊息是6:18: error: expected ';' before 'int'——第 6 行只有 17 個字,第 18 欄就在行尾。cin、cout這種句子少分號,多半是這樣。 - 指在下一行的開頭:往上一行找。像上面的
6:5,第 6 行第 5 欄正是cout的c。宣告變數的句子少分號,多半是這樣,而且訊息不一定寫expected ';',也可能是expected ',' or ';'或expected initializer。
¶✘ 錯誤 2:'某個名字' was not declared in this scope
這是最常見的編譯錯誤,意思是「你用了一個編譯器不認得的名字」。同一句訊息,常見有兩種原因:
(a) 用了 cout/cin,卻沒寫 #include <iostream> 或 using namespace std;
int main() {
cout << "Hello" << endl; // 開頭少了 #include 和 using namespace std
return 0;
}
→ hello.cpp:2:5: error: 'cout' was not declared in this scope(接著第 2 行的 endl 也會被報一次)
解決:補上開頭兩行 #include <iostream> 和 using namespace std;。
(b) 用了某個變數,卻忘了先宣告它
#include <iostream>
using namespace std;
int main() {
cin >> a; // a 沒有宣告
return 0;
}
→ add.cpp:5:12: error: 'a' was not declared in this scope
解決:使用前先宣告,例如 int a;。
看到
... was not declared in this scope,就照這三點檢查:名字打錯了嗎?該宣告的變數宣告了嗎?該#include的加了嗎?
¶✘ 錯誤 3:cin、cout 的箭頭方向寫反
#include <iostream>
using namespace std;
int main() {
int a;
cin << a; // 讀入要用 >>,這裡寫成了 <<
return 0;
}
錯誤訊息:
add.cpp:6:9: error: no match for 'operator<<' (operand types are 'std::istream' {aka 'std::basic_istream<char>'} and 'int')
這句後面還會跟著一大串 note: 和第二個 error,先看第一句就好:第 6 行、cin << a 這個組合不成立。
解決:讀入用 cin >>、印出用 cout <<——箭頭指向資料要去的地方(1.3 的箭頭說明)。反過來寫 cout >> a 也會得到同樣形式的訊息(no match for 'operator>>')。
¶✘ 錯誤 4:型態不符(型態錯誤)
#include <iostream>
using namespace std;
int main() {
int a = "abc"; // 想把一段文字塞進「整數」變數
cout << a << endl;
return 0;
}
錯誤訊息:
add.cpp:5:13: error: invalid conversion from 'const char*' to 'int' [-fpermissive]
解決:型態要對得上——int 變數只能放整數,不能直接塞文字。
¶如何讀錯誤訊息
- 看行號:錯誤在第幾行,定位到那一行
- 看欄號:在那一行的第幾個字元(有時不精確,但能縮小範圍)
- 看訊息:理解編譯器在說什麼。訊息裡的
numeric constant、string constant、'operator<<'、token這些詞,就是 1.5 的 token 類型(名字/識別碼在訊息裡常寫成unqualified-id) - 修改並重新編譯:改完一個錯誤後,重新編譯,可能會發現新的錯誤
動手試試看:
- 故意在程式裡製造上面講過的幾種錯誤(漏分號、漏
#include/using namespace std;、用了沒宣告的變數、箭頭寫反、型態放錯…),看看編譯器各自怎麼報 - 試著只看錯誤訊息,自己找出問題並修好
自我檢測
讀完這一節,做做看下面 3 題,送出後馬上看得到解說。
下面的程式編譯失敗:
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
int sum = a + b
cout << sum << endl;
return 0;
}
錯誤訊息是:
add.cpp:8:5: error: expected ',' or ';' before 'cout'
要怎麼修?
下面的程式編譯失敗,訊息是 add.cpp:5:12: error: 'a' was not declared in this scope。怎麼修?
#include <iostream>
using namespace std;
int main() {
cin >> a;
int a;
cout << a << endl;
return 0;
}
下面這一行會怎樣?
int a = "abc";