I have a class with a static char array.
The size of the array is given to me in argv.
I want to do somthing like this:
class ABC {
public:
static char *buffer;
ABC(int size) {
ABC::buffer = new char[size];
}
}
// in other file:
ABC tempVar(atoi(argv[1]));
but this doesn’t seem to work. I get errors like:
Error 2 error LNK2001: unresolved external symbol “public: static char
* ABC::buffer” (?buffer@ABC@@2PADA) gpslib.lib
How can I fix this?
You need to define the
static bufferexactly once, it has only been declared. Add the following to exactly one.cppfile:Note that everytime an instance of
ABCis created, the previously allocatedbufferwill be lost (a memory leak) which is not what you want.A more robust solution would have
bufferas an instance (non-static) member. An even more robust solution would usestd::stringinstead of achar*and have dynamic memory allocation managed for you.