gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:48:20 25 4
gpt4 key购买 nike

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

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

主要.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!");
}

当我运行它时,我希望在串行日志中看到两行:做了什么!有输出吗?但我只看到是否有输出。所以很明显 MYDEBUG 的定义在包含的头文件中不可用。为什么?

我以前见过类似的东西,他们使用#define 作为在包含的头文件中设置内容的方式,例如: https://github.com/FastLED/FastLED/wiki/ESP8266-notes

我在这里监督什么?

提前致谢,蒂莫

最佳答案

您对 MYDEBUG 的定义在main.cpp只影响 main.cpp 中的代码在#define之后.它对您编译的任何其他文件都不可见。

做你想做的事情的最好方法是将定义添加到你的 platformio.ini文件。

尝试在您的项目部分中添加如下所示的行:

build_flags = -DMYDEBUG

如果你需要设置MYDEBUG到一个特定的值,你会把它写成:

build_flags = -DMYDEBUG=23

这将告诉编译器定义常量 MYDEBUG对于它编译的每个文件。

关于C++:在包含的头文件中使用#define 常量 (Arduino),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55885777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com