0

I am trying to create a library, where I have an array of pointers to functions in it. This array is used by other functions in the library. This is the code of the header file:

class Lib {
  public:
    static void call();
    static void (*caller[])();
  private:
};

This is the code of the .cpp-file:

#include "Lib.h"

void (*caller[2])();

void Lib::call() {
  caller[0]();
}

The sketch executing this is

#include <Lib.h>

void setup() {
  Lib::call();
}

void loop() {}

When I try to compile this, I get the following error:

undefined reference to `Lib::caller'
collect2: error: ld returned 1 exit status
Mehrere Bibliotheken wurden für "Lib.h" gefunden

Another weird thing is that the error about the multiple found libraries goes away if I take away the line

Lib::call();

However, if I put the same code directly into the sketch like so:

void (*caller[2])();

void call() {
  caller[0]();
}

void setup() {
  call();
}

void loop() {}

I get no error. What's the problem here?

1 Answer 1

0
void (*caller[2])();

should be:

void (*Lib::caller[2])();

Since you are defining storage space for a static member variable you have to tell the compiler what class it's a static member of.

5
  • Thanks, that solves the part about the undefined reference. How does the problem with the multiple libraries originate from this though?
    – LukasFun
    Commented Oct 30, 2019 at 12:00
  • Probably because you do have two libraries named Lib.h somewhere?
    – Majenko
    Commented Oct 30, 2019 at 12:06
  • (incidentally, I don't speak german, so had no clue what you were on about at first about multiple libraries...)
    – Majenko
    Commented Oct 30, 2019 at 12:09
  • No, there is just one Lib.h file. The funny thing is, that, as I wrote, this error goes away when not calling the function in the sketch. And it also goes away with your solution. I was just wondering where it originated from.
    – LukasFun
    Commented Oct 30, 2019 at 12:49
  • Probably some bug in the IDE then...
    – Majenko
    Commented Oct 30, 2019 at 13:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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