Arduino: struct pointer as function parameter

Peter B picture Peter B · Jul 5, 2013 · Viewed 11.2k times · Source

The code below gives the error:

sketch_jul05a:2: error: variable or field 'func' declared void

So my question is: how can I pass a pointer to a struct as a function parameter?

Code:

typedef struct
{ int a,b;
} Struc;


void func(Struc *p) {  }

void setup() {
  Struc s;
  func(&s);
}

void loop()
{
}

Answer

A.H. picture A.H. · Jul 5, 2013

The problem is, that the Arduino-IDE auto-translates this into C like this:

#line 1 "sketch_jul05a.ino"
#include "Arduino.h"
void func(Struc *p);
void setup();
void loop();
#line 1
typedef struct
{ int a,b;
} Struc;


void func(Struc *p) {  }

void setup() {
  Struc s;
  func(&s);
}

void loop()
{
}

Which means Struc is used in the declaration of func before Struc is known to the C compiler.

Solution: Move the definition of Struc into another header file and include this.

Main sketch:

#include "datastructures.h"

void func(Struc *p) {  }

void setup() {
  Struc s;
  func(&s);
}

void loop()
{
}

and datastructures.h:

struct Struc
{ int a,b;
};