-2

I have the following code:

class employee {
public:
    static int last_id;
    ...

};

 int main() {
    employee::last_id=0;
 }

When i try to run it it gives the following error:

Undefined symbols for architecture x86_64:
  "employee::last_id", referenced from:
      _main in chap7-F3IpS1.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
[Finished in 0.3s with exit code 1]
Petru
  • 500
  • 6
  • 19
  • Should have googled this one. I remember running into this error. When I googled it, the first 10 or so results pointed to Stack Overflow. No wonder I could solve this without posting *yet another duplicate.* –  Dec 23 '13 at 19:44

2 Answers2

3
int employee::last_id=0;
int main() {
    [...]

}
manuell
  • 7,528
  • 5
  • 31
  • 58
3

You only declared the static data member but not defined it. Write before main in the global namespace

int employee ::last_id;

It will be initialized by zero though your explicitly can specify the initializer.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • If this data member shall be a constant then it can be initialized in the class definition. In this case it must have the qualifier const. – Vlad from Moscow Dec 23 '13 at 19:39
  • @VladfromMoscov: Almost right. However, an initialization of some static `x` in the class definition does not turn that declaration of `x` into a definition... For an ordinary `const` static an out-of-class definition is then still required if the address is ever taken, explicitly or implicitly (treating `x` as a storage location). However, with C++11 the static `x` can be declared `constexpr`, and initialized in the class definition, and then that's enough for any usage. – Cheers and hth. - Alf Dec 23 '13 at 19:47
  • It's worth noting that there is a special exemption from the One Definition Rule (or rather, this exemption is part of the ODR) for statics in class templates. And this in turn allows a static constant of any type to be defined in a header file, without using a wrapper function and reference. I used to call that an "idiom", but after answering some umpteen questions where it would be natural it became painfully clear that it's absolutely not an idiom, not well known, even though it's just the ordinary C++ rules at play (in a roundabout fashion). ;-) – Cheers and hth. - Alf Dec 23 '13 at 19:50