0

When i write simple C++ code in X-code, it shows Linker Error.

Undefined symbols for architecture x86_64: "Emp::id", referenced from: Emp::Emp() in main.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

#include <iostream>
using namespace std;
class Emp
{

    public:
      static int id;
      int sal;

   Emp()
   {
      Emp::id =10;   // When i comment this line its working fine.
   };
};
int main(int argc, const char * argv[])
{
    Emp Ram;
    cout << Ram.sal ;
    return 0;
 }
mah
  • 39,056
  • 9
  • 76
  • 93
  • This has nothing to do with Xcode: http://ideone.com/M8xtFm. If you add `int Emp::id;` as a line following your class, it will link. – mah Feb 15 '16 at 19:12
  • @mah Comments are not for answering the question. – Lightness Races in Orbit Feb 15 '16 at 20:02
  • @PreferenceBean Show me a rule that states as much? I felt my comment was insufficient as an answer - an answer is not just something to get the poster satisfied, it's something to survive to help others and I don't think my comment does so. – mah Feb 15 '16 at 20:07
  • @mah: If you don't have a complete answer, you don't need to post one. But answers go in the answer section. Comments are for critiquing and for requesting clarification. It says so in many places. I shan't go hunting for the specific quote but feel free to have a browse of the Help Centre to find out how Stack Exchange works. And have a nice night :) – Lightness Races in Orbit Feb 15 '16 at 21:59

1 Answers1

1

You have declared id as a static variable. You then set it in every constructor call, which is probably not what you want to do.

For a 'fix', you can add the following line above main:

int Emp::id = 0;

However, you may not want that to be static. For more information on static class variables, see this page

Signal Eleven
  • 231
  • 1
  • 6
  • Not quite correct. Should be `int Emp::id = 10;` (need type! also, why not initialize to value of `10`?) – crashmstr Feb 15 '16 at 19:30
  • Yes, you are correct of course. I was more concerned with the fact it was marked static at all, as that may not be what the OP really wants... but regardless, I fixed it. – Signal Eleven Feb 15 '16 at 19:59