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

问题描述 投票:1回答:1

我正在使用PlatformIO,我正在为ESP32开发代码。我有一些子库,我希望能够在其中进行调试日志记录。

为了启用调试日志,我认为在main.cpp中通过#define MYDEBUG设置一个常量会很好,然后在包含的库中进行评估。我将代码分解为这个简单的例子:

main.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作为在包含的头文件中设置内容的方法之前我见过类似的东西,例如:qazxsw poi

我在这里监督什么?

提前谢谢蒂莫

c++ arduino esp32
1个回答
1
投票

你在https://github.com/FastLED/FastLED/wiki/ESP8266-notes中对MYDEBUG的定义只会影响main.cpp之后的main.cpp中的代码。它对您编译的任何其他文件都不可见。

您要做的最好的方法是将定义添加到#define文件中。

尝试将类似的行添加到项目的部分:

platformio.ini

如果您需要将build_flags = -DMYDEBUG 设置为特定值,则将其写为:

MYDEBUG

这将告诉编译器为它编译的每个文件定义常量build_flags = -DMYDEBUG=23

© www.soinside.com 2019 - 2024. All rights reserved.