C++:在包含的头文件 (Arduino) 中使用 #define 常量
C++: Use #define constant in included header files (Arduino)
我正在使用 PlatformIO,目前正在为 ESP32 开发代码。我有一些子库,我希望能够在其中进行调试日志记录。
为了启用调试日志,我认为最好在 main 中通过 #define MYDEBUG
左右设置一个常量.cpp然后在包含的库中对其进行评估。我将代码分解为这个简单的例子:
主.cpp:
#include <Arduino.h>
#define MYDEBUG
#include "LedSetup.h"
void setup()
{
Serial.begin(9600);
LedSetup::doSomething();
Serial.println("Is there output?");
}
void loop()
{
}
LedSetup.h:
#ifndef LedSetup_h_
#define LedSetup_h_
#include <Arduino.h>
class LedSetup
{
public:
static void doSomething();
private:
static void logDebug(String message)
{
#ifdef MYDEBUG
Serial.print("LedSetup: ");
Serial.println(message);
#endif
}
};
#endif
LedSetup.cpp:
#include "LedSetup.h"
void LedSetup::doSomething()
{
logDebug("Did something!");
}
当我运行它时,我希望在串行日志中看到两行: Did something!
和Is there output?
但我只看到Is there output
.因此,显然MYDEBUG
的定义在包含的头文件中不可用。为什么?
我之前见过类似的东西,他们使用 #define 作为在包含的头文件中设置内容的一种方式,例如这里:https://github.com/FastLED/FastLED/wiki/ESP8266-notes
我在这里监督什么?
提前感谢,蒂莫
您在main.cpp
中对MYDEBUG
的定义只会影响#define
之后main.cpp
中的代码。它对您编译的任何其他文件都不可见。
您尝试执行的操作的最佳方法是将定义添加到platformio.ini
文件中。
尝试将如下所示的行添加到项目的部分:
build_flags = -DMYDEBUG
如果需要将MYDEBUG
设置为特定值,请将其编写为:
build_flags = -DMYDEBUG=23
这将告诉编译器为其编译的每个文件定义常量MYDEBUG
。
相关文章:
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 什么时候在C++中返回常量引用是个好主意
- 为什么使用类型化的 8 位常量而不是等效的 #define "Impossible constraint"?
- 错误:数字常量 #define BOOT_PROTOCOL 0x00 之前的预期'>'
- 使用常量生成的代码比 #define 小的示例
- C++:在包含的头文件 (Arduino) 中使用 #define 常量
- 为什么我们不能在声明之前使用预处理器 #define 常量
- 使用来自其他方法和 #define 的函数定义常量
- C++ #define 和常量变量相乘时出错
- 如何从预定义常量中获取 #define 符号而不是值
- 循环通过常量枚举#define
- 常量是否比通常使用 #define 更多或更少的内存
- Visual Studio,错误:在数组声明中使用 #define 常量时,应使用"]"
- 定义复常数 "i" C++(#define vs 常量)
- 根据编译时常量,使用相同的标识符 #define 或类型定义是否被认为是可接受的做法?
- 为什么调试器不知道 #define 常量?
- 如何删除#define使用在c++数组常量
- 使用#define声明常量的好处是什么?
- 常量字符串与 #define