Arduino - 为什么结构超出范围?

Arduino - struct out of scope why?

我和我的 arduino MEGA 一起在电机程序中工作(我必须控制多个电机,这就是我使用该结构的原因)。 我不明白为什么当我在驱动函数中将它用作参数时 MOTOR 超出范围:

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

编辑:我最初的回答做出了一些假设,即 Arduino IDE 比实际情况更接近 AVR-GCC。对于熟悉 C 或 C++ 并使用这些芯片进行大量工作的任何人,我的一般建议是直接使用 Atmel studio 和 AVR-GCC,因为这样可以 运行 减少问题。

Arduino 实际上是 C++,但它会在将您的代码转换为为芯片编译的 C++ 代码之前进行一些预处理(例如从 setuploop 创建 main ).您遇到的问题是由预处理步骤引起的,由 .

解释

作为更一般的 c++ 用法说明,我建议将您的结构定义更改为:

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

您可能想阅读 Difference between 'struct' and 'typedef struct' in C++? 以了解为什么在 c++ 中有些不同。

因为通往地狱的道路是用善意铺就的

A​​rduino IDE 试图通过在代码开头为所有用户定义的函数生成原型来提供帮助。当这些原型之一引用用户定义的类型时,事情就会以描述的方式爆炸。

诀窍是让代码无法被 IDE:

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

IDE 遇到了 namespace 并且不知道如何处理后面的块,所以跳过它。

我建议这应该和名称空间选项一样好?

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);
}