这是如何在 Arduino IDE 中编译的?

问题描述

我注意到以下代码,显然是无效的 C++,在 Arduino IDE 中编译(使用 AVR-GCC):

// The program compiles even when the following
// line is commented.
// void someRandomFunction();


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

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

}

void someRandomFunction() {
}

这里发生了什么? C++ 要求函数在使用前先声明。当编译器遇到 someRandomFunction() 函数中的 setup() 行时,它如何知道它将被声明?

解决方法

这就是我们所说的前向声明,在 C++ 中,它只要求您在尝试使用之前声明函数的原型,而不是定义整个函数。:

以下面两段代码为例:

代码 A:

#include <Arduino.h>
void setup(){}
void AA(){
  // any code here
}
void loop(){
  AA();
}

代码 B:

#include <Arduino.h>
void setup(){}
void loop(){
  BB();
}
void BB(){
  // any code here
}

严格来说,C 要求函数前向声明,以便编译器编译和链接它们。所以在 CODE A 中,我们没有声明函数而是定义了函数,这使得它对于正确的 C 代码是合法的。但是 CODE B 在循环之后有函数定义,这对于普通 C 来说是非法的。解决方案如下:

#include <Arduino.h>

void BB();

void setup(){}
void loop(){
  BB();
}
void BB(){
  // any code here
}

然而,为了适应 Arduino 脚本格式,在 void loop() 之后有一个 void setup(),需要 Arduino 在其 IDE 中包含一个脚本,该脚本会自动查找函数并为您生成最上层的原型您无需担心。因此,尽管是用 C++ 编写的,但您不会经常在其草图中看到使用前向声明的 Arduino 草图,因为它运行良好,并且通常更容易阅读第一次 setup() 和 loop()。

,

您的文件是 .ino 而不是 .cpp。 .ino 是“Arduino 语言”。

带有附加 ino 文件 are processed by the Arduino builder 的主 ino 文件到 C++ 源代码,然后才作为 C++ 处理(预处理器、编译)。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...