Code Fix

中級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'

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

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

undefined reference to 'Class::member' の原因と直し方(staticメンバ変数)

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

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

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