How to expose instance to be used by another class

Hi, I have a RTC class that has an extern instance.

class DS1307
extern DS1307 RTC;

And I have another class wanting to get the time from this class by calling RTC.getTime() and so on. I found out this is not enough, I'd get an "'RTC' was not declared in this scope" error. So how do I make it so RTC.getTime() can be called from anywhere from another class to the arduino sketch?

Maybe make getTime() a static method and not do an instance RTC?


If you are moving things to separate libraries, you need to include the definitions for class DS1307 and RTC so that the library can see it. Typically this would be done in a common include file.

In file.h you would have:

class DS1307
    // ....

extern DS1307 RTC;

and it file.cpp you would have:

// Define RTC
DS1307 RTC;

Note, when you have .cpp files, you need to make sure you have the prototypes for the functions declared before they are used, since this is something the IDE does behind your back for .ino/.pde files.

At the advanced C++ level, there are the concepts of public, private, and friend, superclasses, subclasses that can be used, but that is probably a more complex task.

Thanks. That did it. I just needed to #include the DS1307.h.

I'm already extending 2 other classes. I thought doing this way would be easier since the DS1307 can have a constructor and can be accessed on the main sketch too.

Hi, this compiles fine but crashes the arduino when it starts up. Sorry, no error message except garbled text in the serial monitor. I'm using the extern RTC instance in another class like so.


#include "../DS1307new/DS1307new.h"

void Device::checkTimedEvent() {
  //.... and so on

The arduino is fine when I comment out the RTC.. I guess this shouldn't be done.

Not sure what should be done. I guess I'll turn the RTC.getTime() into a static function and see.