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– chrisl2019年12月09日 21:56:03 +00:00Commented Dec 9, 2019 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– LukasFun2019年12月09日 21:58:01 +00:00Commented Dec 9, 2019 at 21:58
-
your Lib.h is wrong. it broke the automatic forward declarations generationJuraj– Juraj ♦2019年12月10日 05:53:52 +00:00Commented Dec 10, 2019 at 5:53
-
it compiles in Arduino IDE 1.8.10 with empty Lib.hJuraj– Juraj ♦2019年12月10日 12:10:28 +00:00Commented Dec 10, 2019 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– Juraj ♦2019年12月11日 08:25:25 +00:00Commented Dec 11, 2019 at 8:25
1 Answer 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() {}
-
1Note: These declarations (
static void foo1()
andstatic void foot2()
are called forward declarations.Michel Keijzers– Michel Keijzers2019年12月09日 22:05:38 +00:00Commented Dec 9, 2019 at 22:05