Search code examples
c++classstaticinitializer

Initializing a static class member


I'm trying to initialize a static class member and having no luck. Here's a test:

file Test.h

#include <string>

class Test {

public:
    static void init(char*);

private:
    static std::string  *sp;

};

file Test.cpp

#include "Test.h"

// Initialize the class
void
Test::init(char *foo) {
    Test::sp = new std::string(foo);
}

int main(int argc, char** argv) {
    Test::init(argv[1]);  // call the class initializer
}

The linker fails with:

Undefined symbols for architecture x86_64:
  "Test::sp", referenced from:
      Test::init(char*) in Test-OK13Ld.o
ld: symbol(s) not found for architecture x86_64

In the real world, init() is going to do some real work to set the static member. Can someone point out the error?


Solution

  • This is a bit of an embarrassing "feature" of C++: you need to do some hand holding to make sure the linker can generate the symbols. You need to choose some cpp file, and make sure that no such handholding occurs for the same symbols in any other (otherwise the linker will fail when it encounters duplicate symbols). So you have to do another declaration of the static member variables for your class in the cpp file like this:

    std::string * Test::sp; // or sp = NULL;