[英]How does this compile in 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++ 要求函数在使用前声明。 当编译器到达setup()
function 中的someRandomFunction()
() 行时,它如何知道它将被声明?
这就是我们所说的前向声明,在 C++ 中,它只需要您在尝试使用它之前声明 function 的原型,而不是定义整个 function。:
以下两段代码为例:
代码 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 中我们没有声明 function 但它定义了,这使得正确的 C 代码合法。 但是代码 B 在循环后有 function 定义,这对于普通的 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 的草图中看到经常使用前向声明的草图,因为它运行良好,并且通常更容易阅读首先设置()和循环()。
你的文件是.ino 不是.cpp。 .ino 是“Arduino 语言”。
带有附加 ino 文件的主 ino 文件由 Arduino 构建器处理为 C++ 源,然后才处理为 C++(预处理器,编译)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.