Arduino - struct out of scope why?

2019-08-10 21:10发布

问题:

I work at a motor programm (and i have to control multiple motors thats why i use the struct) together with my arduino MEGA. I dont't understand why MOTOR is out of scope when I use it as argument in the drive function:

typedef struct motor
{
   int EN;
   /*some more ints*/
}MOTOR;

MOTOR mot1;
MOTOR mot2; /*this works with no compile error*/
int drive (MOTOR*) /*here i have compile error out of scope, neither with or without pointer*/
{
   return 1;
}

void setup()
{}

void loop()
{}


sketch_jul25a:2: error: 'MOTOR' was not declared in this scope
sketch_jul25a:2: error: expected primary-expression before ')' token
sketch_jul25a.ino: In function 'int drive(MOTOR*)':
sketch_jul25a:9: error: 'int drive(MOTOR*)' redeclared as different kind of symbol
sketch_jul25a:2: error: previous declaration of 'int drive'
'MOTOR' was not declared in this scope

回答1:

Because the road to hell is paved with good intentions.

The Arduino IDE tries to be helpful by generating prototypes for all user-defined functions at the beginning of the code. When one of these prototypes references a user-defined type, things blow up in the manner described.

The trick is to make the code unparseable by the IDE:

namespace
{
  int drive (MOTOR*)
  {
     return 1;
  }
}

The IDE runs into namespace and has no idea what to do with the block that follows, so skips it.



回答2:

And i suggest this should do the job as good as the namespace option?

struct motor
{
   int EN;
   /*some more ints*/
};
int drive (motor* mtr);
motor mot1;
motor mot2; /*this works with no compile error*/

  int drive (motor* mtr)
  {
   return 1;
  }


void setup()
{}

void loop()
{
  int a = drive(&mot1);
}


回答3:

EDIT: My original answer made some assumptions that Arduino IDE was closer to AVR-GCC than it actually was. My general recommendation for anyone who is familiar with C or C++ that is doing a lot of work with these chips is to use Atmel studio and AVR-GCC directly as you will run into less issues this way.

Arduino is actually C++ underneath but it does some preprocessing before it turns your code into the C++ code that gets compiled for the chip (like creating main from setup and loop). The issue you have is due to a preprocessing step and is explained by Ignacio Vazquez-Abrams' answer.

As a more general c++ usage note I'd recommend changing your struct definition to this:

struct motor
{
   int EN;
   /*some more ints*/
};

You might want to read Difference between 'struct' and 'typedef struct' in C++? to see why things are a bit different in c++.



标签: c arduino