How to share a class among multiple files?

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

Isn't it

void fc::fromFoo();

or similar?

Edit - oh I guess not in a class definition...

The C++ compiler compiles each source file separately (but see below), so when it's compiling bar.cpp it doesn't know what fc is. So you need need to tell the compiler what fc is in bar.cpp:

extern foobarClass fc;

There is one exception to compiling each source file separately: Arduino combines all .ino files together and does a bit of processing to automatically add function declarations and such. But all .cpp files are compiled separately even in Arduino.

The fc variable must be known to all code using fc.
You can put it in a shared header file like

external foobarClass fc;

Then the compiler knows the type of the fc variable and how to use its methods.

Wow... Not only fast, but options too.

I tried it with extern and it works fine

I tried it by renaming the .cpp files to .ino and that works

I tried it by passing fc to the bar functions and that works

Thank you all for the great responses.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.