0

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136
kakush
  • 3,334
  • 14
  • 47
  • 68
  • You don't want to do something like that. Buggy. –  Jun 28 '12 at 13:56
  • What purpose would it serve? I don't see any point. Also, avoid using `atoi`. Use `std::stoi` (introduced by C++11). – Nawaz Jun 28 '12 at 13:56
  • @Nawaz - what is the difference? – kakush Jun 28 '12 at 14:04
  • 1
    @kakush: Difference is that `std::stoi` will let you know if the argument is invalid (or there is overlow), while `std::atoi` will be silent. – Nawaz Jun 28 '12 at 14:13
  • @VladLazarenko - I'm using this buffer somewhere else - that's why it is static. and I have only one instance of this class - so there should not be any bugs. – kakush Jun 28 '12 at 14:28

1 Answers1

5

You need to define the static buffer exactly once, it has only been declared. Add the following to exactly one .cpp file:

char* ABC::buffer;

Note that everytime an instance of ABC is created, the previously allocated buffer will be lost (a memory leak) which is not what you want.

A more robust solution would have buffer as an instance (non-static) member. An even more robust solution would use std::string instead of a char* and have dynamic memory allocation managed for you.

hmjd
  • 120,187
  • 20
  • 207
  • 252