With the following 5 files, compiling throws an error in bar.cpp because the fc in fc.fromFoo(); is not defined. If foobarClass fc; is also placed in bar.cpp, the failure is duplicate definition of fc. If it is placed only in foobarClass.h, again that is a duplicate fc error.
How does one share a class amongst multiple files?
foo.ino
#include "foobarclass.h"
#include "bar.h"
foobarClass fc;
void setup() {
Serial.begin(115200);
delay(500);
fc.fromFoo(); // print "This came from Foo" (from the class)
fc.fromBar(); // print "This came from bar" (from the class)
fromFoo(); // print "This came from Foo" (from bar.cpp)
fromBar(); // print "This came from bar" (from bar.cpp)
}
void loop() {}
bar.cpp
#include "foobarclass.h"
void fromFoo() {
fc.fromFoo();
}
void fromBar() {
fc.fromBar();
}
bar.h
#ifndef __BAR_H__
#define __BAR_H__
void fromFoo();
void fromBar();
#endif
foobarclass.cpp
#include <arduino.h>
#include "foobarclass.h"
foobarClass::foobarClass() {}
void foobarClass::fromFoo() {
Serial.println("This came from Foo");
}
void foobarClass::fromBar() {
Serial.println("This came from Bar");
}
foobarclass.h
#ifndef __FOOBARCLASS_H__
#define __FOOBARCLASS_H__
#include <arduino.h>
class foobarClass
{
public:
String msg = "It is foobar";
foobarClass();
void fromFoo();
void fromBar();
};
#endif