如何解决这是如何在 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++ 处理(预处理器、编译)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。