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
1 Answer 1
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 atemplate
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() {
}
-
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– timemage2021年04月12日 20:59:33 +00:00Commented Apr 12, 2021 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 :)guyd– guyd2021年04月13日 03:30:28 +00:00Commented Apr 13, 2021 at 3:30
.h
file." You mean#include
it?inline
or a template class.