c++arduinoesp32fastled

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


I'm using PlatformIO and I'm currently developing code for an ESP32. I have some sub libraries in which I want to be able to do debug logging.

To enable the debug log I thought it would be nice to set a constant via #define MYDEBUG or so in the main.cpp which then is evaluated inside the included libraries. I broke my code down to this simple example:

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

When I run this I would expect to see two lines in the serial log: Did something! and Is there output? But I only see Is there output. So obviously the define of MYDEBUG is not available in the included header file. Why?

I have seen something similiar before where they use #define as a way of setting up things in included header files, for example here: https://github.com/FastLED/FastLED/wiki/ESP8266-notes

What am I overseeing here?

Thanks in advance, Timo


Solution

  • Your definition of MYDEBUG in main.cpp only affects the code in main.cpp after the #define. It's not visible to any other files you compile.

    The best way to do what you're trying to do is to add the define to your platformio.ini file.

    Try adding a line that looks like this to the section for your project:

    build_flags = -DMYDEBUG
    

    If you needed to set MYDEBUG to a specific value you'd write it as:

    build_flags = -DMYDEBUG=23
    

    This will tell the compiler to define the constant MYDEBUG for every file it compiles.