为什么我不能在 Arduino 中传递 typedef 或枚举?

Why can't I pass typedef or enum in Arduino?

本文关键字:typedef 枚举 不能 Arduino 为什么      更新时间:2023-10-16

以下草图在Arduino环境中编译失败。

假设typedefs可以在Arduino软件中使用,自动原型生成是导致故障的潜在机制吗?如果是这样的话,那它是什么?为什么Arduino没有提供一个围绕C++的轻量级包装器?

#define PRODUCE_WACKY_COMPILETIME_ERROR
typedef int MyMeaningfulType;
#ifndef PRODUCE_WACKY_COMPILETIME_ERROR
void myFunc(MyMeaningfulType myParam);
#endif
void myFunc(MyMeaningfulType myParam)
{
  myFunc(10);
}
void setup() {}
void loop() {}

为了搜索引擎的利益,报告的错误是:

error: variable or field 'myFunc' declared void
error: 'MyMeaningfulType' was not declared in this scope

请参阅http://arduino.cc/en/Hacking/BuildProcess具体报价是:

This means that if you want to use a custom type as a function argument, you should declare it within a separate header file.

本页很好地解释了Arduino语言与C/C++在工作/预处理文件方面的不同。

他们正试图为找到的每个函数创建原型。不幸的是,如果在函数之前在文件中定义typedef,并在函数定义中使用它,那么他们放置函数原型的地方看不到它,这会产生语法错误。

如果在这些函数定义中使用"struct*"语法,您将受益于C的"不透明类型"功能,在该功能中,您可以使用结构定义,而无需事先声明。因此,构建typedef,使用它,但在任何在参数中使用typedef的函数中使用结构定义。

typedef struct mytype_ {
    int f1;
} mytype_t;
void myfunc(struct mytype_ * xxx) {
    xxx->f1 = 1;
}