Chr*_*ris 2 arduino arduino-ide
我希望有人能解释为什么这段代码不能在 Arduino IDE 中编译(使用 1.0.5)。以下代码仅在 DEBUG=1 时编译,但在设置为 0 时编译。
我希望实现的只是一种在我交换 LED 驱动器时使用相同代码的简单方法,并在重新编译和上传之前翻转 DEBUG 位。
注意:本示例是IDE中要编译的全部代码(不需要其他代码)。
问题代码:
#define DEBUG 0 //DEBUG=1 works, DEBUG=0 causes compiler error
#if DEBUG == 1
int x = 123;
//Adafruit_8x8matrix matrix = Adafruit_8x8matrix();
#else
int x = 567;
//Adafruit_BicolorMatrix matrix = Adafruit_BicolorMatrix();
#endif
void setup() { }
void loop() { }
Run Code Online (Sandbox Code Playgroud)
错误:
core.a(main.cpp.o): In function `main':
C:\arduino\hardware\arduino\cores\arduino/main.cpp:11: undefined reference to `setup'
C:\arduino\hardware\arduino\cores\arduino/main.cpp:14: undefined reference to `loop'
Run Code Online (Sandbox Code Playgroud)
原因是 Arduino IDE 很烂。在引擎盖下它会像这样生成 c 代码
#define DEBUG 0 //DEBUG=1 works, DEBUG=0 causes compiler error
#if DEBUG == 1
int x = 123;
//Adafruit_8x8matrix matrix = Adafruit_8x8matrix();
#else
int x = 567;
//Adafruit_BicolorMatrix matrix = Adafruit_BicolorMatrix();
#endif
void setup() { }
void loop() { }
Run Code Online (Sandbox Code Playgroud)
因此,如果 debug==0,编译器将看不到生成的函数原型。只需将编译器输出设置为详细,然后自己查看构建目录中生成的代码。
解决所有这些痛苦的方法是找到一些方法来阻止 IDE 干扰你的东西。过去,我使用 TRICK17 宏解决了函数原型的一些类似问题(有关详细信息,请参见此处)。我不会进入这个宏的混乱实现,因为现在我找到了一个非常出色的解决方案。
因此新的解决方案是
namespace {
// name of namespace left empty --> this is the anonymous namespace
// now the IDE will not mess with our stuff
#define DEBUG 0 //DEBUG=1 works, DEBUG=0 causes compiler error
#if DEBUG == 1
int x = 123;
//Adafruit_8x8matrix matrix = Adafruit_8x8matrix();
#else
int x = 567;
//Adafruit_BicolorMatrix matrix = Adafruit_BicolorMatrix();
#endif
}
void setup() { }
void loop() { }
Run Code Online (Sandbox Code Playgroud)