c++ - 这如何在 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()。
推荐阅读
- firebase - Firestore 安全 .data 规则不起作用
- html - 如何使表格单元格拉伸其余宽度?
- javascript - 为什么在 javascript 中创建对象时必须使用“new”?
- python - Django中的自定义登录表单
- c++ - 可以将继承的类设为 const 吗?
- python-3.x - 我无法训练逻辑运算 xor
- java - 没有得到 ListIterator 的输出
- sql - 我需要在 sybase 中编写 Update 语句
- java - Hibernate 在 ManyToOne 关系上插入重复的行
- javascript - 使用 javascript 按索引重新排序数组