1

In .ino file I have a class defined (called IPmonitoring).Also, inside the same .ino file, I call a .h file ( which is located "above" class IPmonotoring).

When I try to call members of IPmonitoring inside .h file - I get an error, which usually I solve using extern, but seemingly it is not the same for classes.

What should be done ?

Guy

4
  • the class definition is then not included in the .h file. So normally you would define that class in another .h file and then let the first .h file include the second .h file with the class definition.
    – chrisl
    Apr 12 at 19:42
  • 1
    I don't know what you mean by "call a .h file." You mean #include it?
    – timemage
    Apr 12 at 19:49
  • You should not have code in a .h file unless it's inline or a template class.
    – Majenko
    Apr 12 at 19:52
  • @timemage - yes
    – Guy . D
    Apr 12 at 20:09
2

You need to re-think your layout, and your usage of the .h file.

  • You should never have code in a .h file unless it is either inline or part of a template class.

A .h file should only contain hints about where other things are. Those things should then be in .cpp or .ino files.

For example your IPmonitoring class would be declared in a .h file, and defined (or implemented) in a .cpp file (or .ino file if you prefer). Any place you want to use that class you #include the .h file. In one place you may choose to create an instance of that class. It is that instance that you then reference with extern.

In the Arduino world it is common to create a single instance of the class in the class's .cpp file and extern it in the .h file so everywhere that you include the .h file instantly has access to that single instance of the object.

This is how most libraries are written.

For example:

// IPMonitoring.h

class IPMonitoring {
    public: 
        void doStuff();
};

extern IPMonitoring ipMon;

And:

// IPMonitoring.cpp

#include <IPMonitoring.h>

IPMonitoring ipMon;

void IPMonitoring::doStuff() {
    // Do something
}

And finally:

// mySketch.ino

#include <IPMonitoring.h>

void setup() {
    ipMon.doSomething();
}

void loop() {
}
2
  • class templates are instantiated to create classes; likewise for function templates and functions. The involvement of a template doesn't affect things beyond being an incentive to inline, since the export keyword never really took off and then was later removed from the standard.
    – timemage
    Apr 12 at 20:59
  • Majenko -Thank you. It all started as .ino file with functions. During writing the code I gathered all function into class, since I wanted 3 instances of it. And the .h file gathers all the function I used for my wifi and MQTT of other class I'm constantly using... well thing started to get messy :)
    – Guy . D
    Apr 13 at 3:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.