0

I have created a library of functions that doesn't have and mustn't have a class. In order to have functions inside the library that can only be called from the library itself, you just write them into the .cpp file and leave them out of the header file completely. Here is the .cpp file of the library (the header file is empty):

#include "Lib.h"

// Definition of foo1
static void foo1(){
    foo2();
}

// Definition of foo2
static void foo2() {}

When including the library in an empty sketch and compiling it I get the following error message:

error: 'foo2' was not declared in this scope

What is the problem here?

  • What does this have to do with Arduino? I think it is a general C/C++ question. Did you write this question and answered it directly for documenting this? – chrisl Dec 9 '19 at 21:56
  • It probably is a question that also applies more broadly, as are many other questions on this site do. Yes, I wrote and answered this question for documentation. – LukasFun Dec 9 '19 at 21:58
  • your Lib.h is wrong. it broke the automatic forward declarations generation – Juraj Dec 10 '19 at 5:53
  • it compiles in Arduino IDE 1.8.10 with empty Lib.h – Juraj Dec 10 '19 at 12:10
  • now I see my error. I thought you have the functions in .ino, but you write it is a .cpp. so in c/c++ you can't use functions defined later in code so you must use forward declarations/function prototypes, but this is how it is 50 years back, so not really an Arduino problem. – Juraj Dec 11 '19 at 8:25
1

When creating a library with functions that are not mentioned in the header file, the order of appearence in the .cpp file suddenly becomes relevant. In order for a function to be used by another function, it has to be declared first.

The first possibility in this example would be to define foo2 before defining foo1 like this:

#include "Lib.h"

// Definition of foo2
static void foo2() {}

// Definition of foo1
static void foo1(){
    foo2();
}

However, this is not only bad practice, it also doesn't always work. If there is any sort of recursive procedure that makes functions call each other, you can't define both of them before the respective other at the same time.

The more elegant and foolproof way to do this is by declaring each function first like you usually would in the header file and then defining what they actually do. The .cpp file of this library would then look like this:

#include "Lib.h"

static void foo1(); // Declaration of foo1
static void foo2(); // Declaration of foo2

// Definition of foo1
void foo1(){
    foo2();
}

// Definition of foo2
void foo2() {}
| improve this answer | |
  • 1
    Note: These declarations (static void foo1() and static void foot2() are called forward declarations. – Michel Keijzers Dec 9 '19 at 22:05

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.