我正在用 C++ 编写 Arduino 草图。我希望用户能够#define
直接在 sketch.ino 文件中的常量,编译代码时需要该常量。 Arduino IDE 使用 g++ 编译器。
假设我们有三个文件:
sketch.ino
sketch.h
sketch.cpp
在 sketch.h 中我定义了
#define OPTION_1 0
#define OPTION_2 1
#define OPTION_3 2
#define OPTION_4 3
#define SLOW 0
#define FAST 1
然后用户在 sketch.ino 中定义 MYOPTION:
#define MYOPTION OPTION_2
在 sketch.h 中,我使用变量来定义宏:
#if MYOPTION == OPTION_1 | MYOPTION == OPTION_2
#define SPEED FAST
#else
#define SPEED SLOW
#endif
在 sketch.cpp 中,我用它来改进时间关键的代码:
MyClass::foo() {
// do something
#if SPEED == FAST
// do more
#if MYOPTION == OPTION_2
// do something extra
#endif
#endif
#if MYOPTION == OPTION_4
// do something else
#endif
}
不幸的是,MYOPTION 的定义似乎在 sketch.cpp 中无法被识别。然而,sketch.cpp 确实可以识别 sketch.h 中定义的变量。有没有办法全局定义预处理器变量,以便可以在使用它们的任何文件中访问它们?
- 将选项定义移至单独的文件,例如选项.h。如果您愿意,您也可以在 sketch.ino 中定义它们。
- 在 sketch.ino 和 sketch.h 中包含 options.h。
- 移动所有依赖的代码
MYOPTION
宏从 sketch.cpp 到 sketch.h。
- Define
MYOPTION
在 sketch.ino 中包含 sketch.h 之前:
#include "options.h"
#define MYOPTION OPTION_2
#include "sketch.h"
以下是使用此技术的流行库的示例:
https://github.com/PaulStoffregen/Encoder https://github.com/PaulStoffregen/Encoder
它允许用户通过草图配置中断的使用ENCODER_DO_NOT_USE_INTERRUPTS
and ENCODER_OPTIMIZE_INTERRUPTS
macros.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)