1

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

Joel Spolsky
  • 33,372
  • 17
  • 89
  • 105
timothy3001
  • 765
  • 2
  • 8
  • 17

1 Answers1

1

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.

romkey
  • 6,218
  • 3
  • 16
  • 12
  • Thank you very much! It's finally working. I still wonder though, how it's working in other libraries then. Like here: https://github.com/FastLED/FastLED/wiki/ESP8266-notes – timothy3001 Apr 28 '19 at 00:22
  • @timothy3001Good question! I'm not entirely sure what's going on in FastLED but one trick you can play is to use the #define's to determine the class that an object belongs to and then instantiate the object in `main.cpp`. That would determine its behavior everywhere in the code even though the #define wouldn't be visible. C++ templates give you even more flexibility with that kind of thing. – romkey Apr 29 '19 at 03:20