'x' undeclared エラー(未宣言の変数)の原因と直し方
宣言していない変数を使ったときに出るエラーです。宣言のタイプミスや、スコープの外で定義した変数を使おうとした場合に起きます。
エラーメッセージの読み方
main.c:4:5: error: 'x' undeclared (first use in this function)
main.c- ファイル名
4- 行番号
5- 列番号 — この位置でgccが構文解析に失敗しました
'x' undeclared (first use in this function)- 内容 — 期待していたもの、または受け付けられなかったもの
このエラーが出る典型パターン
パターン1
1 #include <stdio.h> 2 3 int main(void) { 4 x = 5; ^ 5 printf("%d\n", x); 6 return 0; 7 }
main.c:4:5: error: 'x' undeclared (first use in this function)
変数は使う前に型を付けて宣言する必要があります。代入する行だけでは宣言になりません。
直し方: x を int x にします。
広告
広告スロット(未設定)
パターン2
1 #include <stdio.h> 2 3 int main(void) { 4 int count = 0; 5 total = count + 1; ^ 6 printf("%d\n", total); 7 return 0; 8 }
main.c:5:5: error: 'total' undeclared (first use in this function)
totalという名前をどこにも宣言していないため、コンパイラは未知の識別子として拒否します。
直し方: total を int total にします。
パターン3
1 #include <stdio.h> 2 3 int main(void) { 4 for (i = 0; i < 3; i++) { ^ 5 printf("%d\n", i); 6 } 7 return 0; 8 }
main.c:4:10: error: 'i' undeclared (first use in this function)
for文の初期化部分で使う変数も、あらかじめ型を付けて宣言しておく必要があります。
直し方: i を int i にします。
パターン4
1 #include <stdio.h> 2 3 int main(void) { 4 score = 100; ^ 5 printf("%d\n", score); 6 return 0; 7 }
main.c:4:5: error: 'score' undeclared (first use in this function)
scoreという名前も、型を付けて宣言していなければ未知の識別子として扱われます。
直し方: score を int score にします。
パターン5
1 #include <stdio.h> 2 3 int main(void) { 4 rate = 3.5; ^ 5 printf("%f\n", rate); 6 return 0; 7 }
main.c:4:5: error: 'rate' undeclared (first use in this function)
小数を扱う変数でも同様です。型を明示して宣言する必要があります。
直し方: rate を double rate にします。
よくある誤解
他の言語のように「まず全部読んでから実行」ではなく、Cは上から順に宣言を認識していきます。使う行より後ろで宣言していても、コンパイラにとっては「まだ知らない名前」として扱われます。
実務での勘所
多くの言語(Java、Pythonなど)は、実行や詳細なチェックの前にクラスや関数の名前を一通り集めてから中身を検査するため、定義の順序をあまり気にせず書けます。Cは伝統的に、ソースコードを上から下へ1回だけ読み進めながら翻訳するという設計のため、その時点でまだ読んでいない名前は「存在しない」ものとして扱われます。関数や変数を使う前に宣言(またはプロトタイプ)を書く必要があるのは、この1パスでの処理方式に由来します。