dimanche 24 juillet 2016

implement of service locator pattern in c++ [duplicate]

I want to use this pattern to get global variables instead of namespace or singletone pattern. As I follow the steps of book "game programming pattern", it fails to link. The Link error:

Linking CXX executable main_locator
Undefined symbols for architecture x86_64:
  "Locator::globals_", referenced from:
      Locator::provide(Globals*) in main_locator.cc.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

The code of service locator is below:

// global_locator.hpp
#ifndef GLOBAL_LOCATOR_H_
#define GLOBAL_LOCATOR_H_

class Globals {
public:
  Globals() {this->SetGlobals();}

  int ni;
private:
  void SetGlobals();
};


class Locator {
public:
  static Globals *GetGlobals() {return globals_;}
  static void provide(Globals *globals) {globals_ = globals;}
private:
  static Globals *globals_;
};

#endif

//global_locator.cc

#include "global_locator.hpp"

#include <iostream>

void Globals::SetGlobals() {
  ni = 10;
  std::cout << "call SetGlobals" << std::endl;
}

// main.cc
#include "global_locator.hpp"

#include <iostream>

int main(int argc, char *argv[])
{
  Globals *globals = new Globals();
  Locator::provide(globals);

  Globals *pg1 = Locator::GetGlobals();
  std::cout << pg1->ni << std::endl;

  Globals *pg2 = Locator::GetGlobals();
  std::cout << pg2->ni << std::endl;
  delete globals;
  return 0;
}

Aucun commentaire:

Enregistrer un commentaire