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?

5
  • You don't want to do something like that. Buggy. Commented Jun 28, 2012 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). Commented Jun 28, 2012 at 13:56
  • @Nawaz - what is the difference? Commented Jun 28, 2012 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. Commented Jun 28, 2012 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. Commented Jun 28, 2012 at 14:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.