mercredi 26 juillet 2017

Why is this Singleton design pattern not linking?

The following code is taken directly from "Design Patterns" by Gamma, Helm, Johnson, and Vlissides (1994), with one exception: I have added a public member function named "printOne()" for testing.

I am simply trying to instantiate the singleton object, and invoke the printOne() method thereon.

This code will not link, and I don't know why.

Thank you for your help. Sincerely, Keith :^)

SOURCE

#include <iostream>

class Singleton {
public:
    static Singleton* Instance();
    void printOne() { std::cout << 1 << std::endl; }
protected:
    Singleton();
private:
    static Singleton* _instance;
};

Singleton* Singleton::_instance = 0;
Singleton* Singleton::Instance() {
    if(_instance == 0) {
        _instance = new Singleton;
    }
    return _instance;
}

int main() {

    Singleton::Instance()->printOne();

    std::cout << std::endl;
    return 0;
}

ERROR

Ld /Users/keith/Library/Developer/Xcode/DerivedData/singleton-absganqluliwfnaibrrlstfosfsc/Build/Products/Debug/singleton normal x86_64
    cd /Users/keith/Documents/2017/working/singleton
    export MACOSX_DEPLOYMENT_TARGET=10.11
    /Applications/http://ift.tt/17KlLIW -arch x86_64 -isysroot /Applications/http://ift.tt/1jCtz97 -L/Users/keith/Library/Developer/Xcode/DerivedData/singleton-absganqluliwfnaibrrlstfosfsc/Build/Products/Debug -F/Users/keith/Library/Developer/Xcode/DerivedData/singleton-absganqluliwfnaibrrlstfosfsc/Build/Products/Debug -filelist /Users/keith/Library/Developer/Xcode/DerivedData/singleton-absganqluliwfnaibrrlstfosfsc/Build/Intermediates/singleton.build/Debug/singleton.build/Objects-normal/x86_64/singleton.LinkFileList -mmacosx-version-min=10.11 -stdlib=libc++ -Xlinker -dependency_info -Xlinker /Users/keith/Library/Developer/Xcode/DerivedData/singleton-absganqluliwfnaibrrlstfosfsc/Build/Intermediates/singleton.build/Debug/singleton.build/Objects-normal/x86_64/singleton_dependency_info.dat -o /Users/keith/Library/Developer/Xcode/DerivedData/singleton-absganqluliwfnaibrrlstfosfsc/Build/Products/Debug/singleton

Undefined symbols for architecture x86_64:
  "Singleton::Singleton()", referenced from:
      Singleton::Instance() 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)

BOOK EXCERPT
Design Patterns - Gamma, Helm, Johnson, Vlissides (1994) - pg 129

Design Patterns - Gamma, Helm, Johnson, Vlissides (1994) - pg 129

Aucun commentaire:

Enregistrer un commentaire