Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Member Array in C++

I've created a static member array in class named GTAODV.

static int numdetections[MAXNODES];

However, when I try to access this array within the class methods (examples below),

 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]);

the linker gives an error during compilation:

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

Why does this happen?

like image 555
vigs1990 Avatar asked Dec 04 '22 16:12

vigs1990


1 Answers

When this error occurs it is very likely that you forgot to define your static member. Assuming this within your class definition:

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

Within a a source file:

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

Note the definition outside the declaration in the class.

Edit This should answer the question regarding the "why": static members can exist without the existence of a concrete object, i. e. you can use numdetections without instantiating any object of GTAODV. To enable this external linkage must be possible and thus a definition of the static variable must exist, for reference: Static data members (C++ only).

like image 156
Sebastian Dressler Avatar answered Dec 09 '22 14:12

Sebastian Dressler