2

Please take a look at the program below. Why am I getting an error?

#include <stdlib.h> #include <string> #include <string.h> #include <iostream> using namespace std; class serverData { public: static int serverTemp; static int server; }; int main(int argc, char** argv) { string s = "sajad bahmani"; serverData::server = 90 ; const char * a = s.data(); cout << a[0] << endl; return (EXIT_SUCCESS); } 

In conjunction, I get this error when trying to link:

build/Debug/GNU-Linux-x86/main.o: In function `main': /home/sb23/pr/main.cpp:14: undefined reference to `serverData::server' collect2: ld returned 1 exit status 
2
  • 5
    That is not compile error, that is link error Commented Feb 4, 2010 at 14:36
  • Use s.c_str() to get a "C-style" string from a std::string, s.data() is not guaranteed to be null terminated. Commented Feb 4, 2010 at 14:39

2 Answers 2

8

Static member variables must have storage allocated in one of your .CPP files:

/* static */ int serverData::serverTemp; int serverData::server; 
Sign up to request clarification or add additional context in comments.

Comments

2

You have just declared your static members inside the class but haven't defined them yet. You need to define them outside the class.

//definition int serverData::serverTemp; //implicitly initialized to 0 int serverData::server = 5; // initialized to 5 

2 Comments

Are you sure the first one is initialized?
@Martin: Yes I am pretty sure about it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.