0

I have a singleton class.

In A.h

class single
{
    public:
        static single *Instance;
        static single* getInstance()
        { if(!Instance) Instance = new single; 
          return Instance;
        }
        void hello () { cout<<"Hello"; }
    private: single(){ }
}

In A.cpp

single *single::Instance = 0;
std::auto_ptr <single> SINGLE_OBJ (single::getInstance());

In B.cpp

#include "A.h"

SINGLE_OBJ->hello();

I get the following error: SINGLE_OBJ was not declared in this scope.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user2524261
  • 109
  • 2
  • 10
  • Why is the memory of the instance managed externally through `auto_ptr`? The fact that it is allocated using `new` is an implementation detail. It should be kept internal to `single` for encapsulation, and to ensure that memory is cleaned up even if the user doesn't put the pointer in an `auto_ptr`. By the way, C++11 replaces the deprecated `std::auto_ptr` class template with `std::unique_ptr`. – TheOperator Dec 07 '15 at 11:45

1 Answers1

2

To make SINGLE_OBJ visible in B.cpp you should declare it in A.h. i.e. :

extern std::auto_ptr <single> SINGLE_OBJ;

also, why are you using std::auto_ptr, its deprecated - you should switch to std::unique_ptr.

Guy Avraham
  • 3,482
  • 3
  • 38
  • 50
marcinj
  • 48,511
  • 9
  • 79
  • 100
  • That worked fine when I compiled the code and created a ".o" and a ".so" successfully. But when another application tries to use this ".o" or ".so", I get an error that says Undefined reference to SINGLE_OBJ – user2524261 Dec 07 '15 at 11:46
  • @user2524261 you might want to start a new question, you didnt mention you want to use it in shared library. To me it sounds like some wrong command in compilation ie. look here: http://stackoverflow.com/questions/12748837/c-shared-library-undefined-reference-to-fooclasssayhello – marcinj Dec 07 '15 at 12:47