Question

I have a class, which is not owned by any other classes, therefore accessed via static methods such as addKeyword():

class Foo {

  public:

   /* other public methods and such */

    static void addKeyword(Keyword& keyword);

  private:

    static Foo a;

    std::vector<Keyword> keywords;

    /* Foo's private variables and methods */

    void addKeywordToObject(Keyword& keyword);

}

The idea of doing it like this is I can then call:

//called from elsewhere in the program
void Foo::addKeyword(Keyword& keyword){
  a.addKeywordToObject(keyword);
}

//called from addKeyword() above
void Foo::addKeywordToObject(Keyword& keyword){
  this->keywords.push_back(keyword);
}

And the keyword is added to a's vector of keywords.

However - and I'm sure there's something I'm doing fundamentally wrongly - when I try and compile this code, I get the linker error:

Undefined symbols for architecture x86_64: "Namespace::Foo::a", referenced from:
Namespace::Foo::addKeyword(Namespace::Keyword) in Foo.o.

I have a feeling it's because I'm using the static variable wrongly, but I'm not sure how or why. Could anyone be able to point me in the right direction?

Thanks!

Était-ce utile?

La solution

You need to define the static member in an implementation file.

Foo Foo::a;

Autres conseils

Static data members, are treated as global variables by the compiler, and reside in the data segment as such (only name-wise they are in the class namespace and follow the public/private rules of the class).
The declaration of a static data member in a class is similar to extern for global variables. It tells the compiler that such a variable exists in some translation unit. For the final symbol resolution, the linker needs to actually find the declaration of the variable in some translation unit.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top