Olivier Pons
Olivier Pons

Reputation: 15778

C forward declaration

(NB: it's pure C / Arduino).

I've found tons of links my question, but no one did answer me.

I have a file "Effects.h" and "Keyboard.h".

"Keyboard.h" needs to include "Effects.h". So "Effects.h" can't include "Keyboard.h"

in "Effects.h" I've made those 3 functions:

extern fnKeyPress effectDrops();
extern fnKeyPress effectLineRotate();
extern fnKeyPress effectRainbowCycle();

They all should return a pointer to a function that takes those two parameters: const KeyWithColor *, const struct KeyConfiguration *

So I'm trying to do this:

typedef void (*fnKeyPress)(const KeyWithColor *, const struct KeyConfiguration *);
extern fnKeyPress effectDrops();
extern fnKeyPress effectLineRotate();
extern fnKeyPress effectRainbowCycle();

But is doesn't work because it says:

Effects.h:32: error: 'KeyWithColor' does not name a type
 typedef void (*fnKeyPress)(const KeyWithColor *, const struct KeyConfiguration *);

What is the workaround?

Upvotes: 2

Views: 87

Answers (1)

hroussille
hroussille

Reputation: 419

If you need to forward declare KeyWithColor and (maybe) KeyConfiguration :

(I don't know if your KeyWithColor type is a struct , i will assume that it is for simplicity)

Then place this :

struct KeyWithColor;
struct KeyConfiguration;

Above this :

typedef void (*fnKeyPress)(const KeyWithColor *, const struct KeyConfiguration *);
extern fnKeyPress effectDrops();
extern fnKeyPress effectLineRotate();
extern fnKeyPress effectRainbowCycle();

Doing this you are forward declarating the types too as pointed out in the comment. And basically telling the compiler :

You don't know this yet , but i guarantee that it will be defined

Be carefull to NOT put any kind of implementation in the forward declaration.

Upvotes: 2

Related Questions