4

。という名前のクラスに静的メンバー配列を作成しましたGTAODV

static int numdetections[MAXNODES];

ただし、クラスメソッド(以下の例)内でこの配列にアクセスしようとすると、

 numdetections[nb->nb_addr]++;
 for(int i=0; i<MAXNODES; i++) if (numdetections[i] != 0) printf("Number of detections of %d = %d\n", i, numdetections[i]);

リンカはコンパイル中にエラーを出します:

gtaodv/gtaodv.o: In function `GTAODV::command(int, char const* const*)':
gtaodv.cc:(.text+0xbe): undefined reference to `GTAODV::numdetections'
gtaodv.cc:(.text+0xcc): undefined reference to `GTAODV::numdetections'
gtaodv/gtaodv.o: In function `GTAODV::check_malicious(GTAODV_Neighbor*)':
gtaodv.cc:(.text+0x326c): undefined reference to `GTAODV::numdetections'
gtaodv.cc:(.text+0x3276): undefined reference to `GTAODV::numdetections'
collect2: ld returned 1 exit status

なぜこれが起こるのですか?

4

1 に答える 1

16

このエラーが発生した場合、静的メンバーの定義を忘れている可能性が非常に高くなります。クラス定義内でこれを想定します。

class GTAODV {
public:
    static int numdetections[MAXNODES]; // static member declaration
    [...]
};

ソースファイル内:

int GTAODV::numdetections[] = {0}; // static member definition

クラス内の宣言の外側の定義に注意してください。

編集これは「理由」に関する質問に答える必要があります。静的メンバーは具体的なオブジェクトが存在しなくても存在できます。つまり、のオブジェクトnumdetectionsをインスタンス化せずに使用GTAODVできます。この外部リンケージを有効にするには、静的変数の定義が存在する必要があります。参照用:静的データ メンバー (C++ のみ)

于 2012-04-22T16:55:07.503 に答える