为什么不编译此代码

Why this code does not compile?

本文关键字:代码 编译 为什么不      更新时间:2023-10-16

也许我疯了,但这段代码无法在Arduino IDE 1.0.5&1.0.6.

class Foobar {};
void myFunction(const Foobar& n) {
}
void setup() {
}
void loop() {
}

编译器输出以下错误:

Arduino: 1.0.6 (Windows 7), Board: "Arduino Mega 2560 or Mega ADK"
C:Program Files (x86)Arduinohardwaretoolsavrbinavr-g++ -c -g -Os -Wall -fno-exceptions -ffunction-sections -fdata-sections -mmcu=atmega2560 -DF_CPU=16000000L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106 -IC:Program Files (x86)Arduinohardwarearduinocoresarduino -IC:Program Files (x86)Arduinohardwarearduinovariantsmega C:UsersAlvaroAppDataLocalTempbuild5499093930419069947.tmpMax7219Testing.cpp -o C:UsersAlvaroAppDataLocalTempbuild5499093930419069947.tmpMax7219Testing.cpp.o 
Max7219Testing:2: error: expected ',' or '...' before '&' token
Max7219Testing:2: error: ISO C++ forbids declaration of 'Foobar' with no type

这里怎么了?

哦,我的$DEITY

根据Ignacio的建议,我检查了Arduino生成的最终组装的cpp文件,构建系统尝试编译:

#line 1 "sketch_feb05b.ino"
#include "Arduino.h"
void myFunction(const Foobar& n);
void setup();
void loop();
#line 1
class Foobar {};
void myFunction(const Foobar& n) {
}
void setup() {
}
void loop() {
}

因此,IDE生成函数的声明,并在声明类型之前将它们放在文件的开头。

没有看不见的符号,但Arduino的一个可怕的决定作者:-(

我想知道把类型放在外部头文件中是否能解决这个问题。

代码在这里干净地编译:

http://ideone.com/AuDEQL

class Foobar {};
void myFunction(const Foobar& n) {
}
void setup() {
}
void loop() {
}
int main() {}

如果代码是你发布的,原因通常是

1) 一个不可见的字符(通常是一个控制字符)嵌入在发生错误的前一行中,C++解析器将其作为语法错误

2) 在源文件中看到的字符不是ASCII,而是该字符的某个"幻想"版本(因此可以是Unicode或其他编码)。如果您从使用替代编码使文本"好看"的应用程序(例如,MS word等文字处理程序)中复制和粘贴,就会发生这种情况。

我会把这个文件放在十六进制编辑器中检查,以确保它没有这样的字符。

编辑:Ignacio Vazquez-Abrams在评论中指出的另一种情况是

3) 你可能正在编译一个与你发布的文件不同的文件。Arduino IDE似乎就是这样。