C++:在包含的头文件 (Arduino) 中使用 #define 常量

C++: Use #define constant in included header files (Arduino)

本文关键字:常量 #define Arduino 包含 文件 C++      更新时间:2023-10-16

我正在使用 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