error: 'x' undeclared (first use in this function) の原因と直し方
宣言していない変数を使ったときに出るエラーです。宣言のタイプミスや、スコープの外で定義した変数を使おうとした場合に起きます。
エラーメッセージの読み方
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 にします。
よくある誤解
他の言語のように「まず全部読んでから実行」ではなく、Cは上から順に宣言を認識していきます。使う行より後ろで宣言していても、コンパイラにとっては「まだ知らない名前」として扱われます。
まとめ
error: 'x' undeclared (first use in this function)は初級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。