Code Fix

中級 › staticメンバ変数の undefined reference の原因 › パターン4

staticメンバ変数の undefined reference の原因

クラス内でstaticメンバ変数を宣言しただけで、クラスの外側での実体定義を書き忘れたときにリンクの段階で出るエラーです。

 1  #include <iostream>
 2  class Inventory {
 3  public:
 4      static int total;
 5      Inventory() { total++; }
 6  };
 7  _________________________
                ^
 8  int main() {
 9      Inventory a, b, c;
10      std::cout << Inventory::total << std::endl;
11      return 0;
12  }
undefined reference to `Inventory::total'

空欄を埋めてコンパイル・実行を通す

広告
広告スロット(未設定)

staticメンバ変数の undefined reference の原因

コンパイル自体は通りますが、実行ファイルを作る最後のリンク工程で失敗します。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)