Arduino struct does not name 类型错误

Arduino struct does not name a type error

在 Arduino 中 IDE 我可以用自定义类型创建变量,但不能 return 从函数自定义类型:

这样编译

struct Timer
{
  Timer()
  {
  }
};

Timer t;
void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}
int main()
{
  return 0;
}

这会产生 Timer does not name a type 错误:

struct Timer
{
  Timer()
  {
  }
};

Timer get_timer()
{
  return Timer();
}

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}
int main()
{
  return 0;
}

两者都在 Orwell Dev-Cpp 中编译

我用的是MEGA-2560

您可以阅读 here 关于 Arduino IDE 的构建过程。

在编译之前,您的草图需要转换为有效的 C++ 文件。

此转换的一部分是为所有函数声明创建函数定义。

这些定义放在文件的顶部,在您定义 Time 之前。因此,在 get_timer 的声明点,类型 Time 尚未声明。

克服这个问题的一种方法是将所有类型定义放在一个单独的 .h 文件中,并将其包含到您的草图中。