Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arduino: struct pointer as function parameter

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()
{
}
like image 634
Peter B Avatar asked Mar 23 '23 06:03

Peter B


1 Answers

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;
};
like image 133
A.H. Avatar answered Mar 25 '23 20:03

A.H.