中級 › undefined reference to 'Class::member' の原因と直し方(staticメンバ変数) › パターン1
undefined reference to 'Class::member' の原因と直し方(staticメンバ変数)
クラス内でstaticメンバ変数を宣言しただけで、クラスの外側での実体定義を書き忘れたときにリンクの段階で出るエラーです。
1 #include <iostream> 2 class Counter { 3 public: 4 static int total; 5 Counter() { total++; } 6 }; 7 _______________________ ^ 8 int main() { 9 Counter a, b; 10 std::cout << Counter::total << std::endl; 11 return 0; 12 }
undefined reference to `Counter::total'
空欄を埋めてコンパイル・実行を通す
クラス内のstatic int total;はあくまで宣言です。実体(メモリ上の場所)はクラスの外側で一度だけ定義する必要があり、忘れるとコンパイルは通ってもリンクで失敗します。
次の問題