Passing defines in include files?

I’m trying out multiple .cpp and .h files for a project using an Arduino Nano.

I’ve got the basic idea of using multiple cpp and include files but missing something for defines.

main.cpp

#include <Arduino.h>

#include <test.h>

#define DEBUG

void setup()

{

Serial.begin(9600);

Serial.println("TEST");

#ifdef DEBUG

Serial.println("Setup");

#endif

}

void loop()

{

testPrint();

delay(1000);

}

test.h

extern void testPrint();

test.cpp

#include <Arduino.h>


void testPrint()
{
#ifdef DEBUG
    Serial.println("testPrint");
#endif
}

How do I get the define DEBUG working in the test.cpp.
Its defined in the main.cpp file but not in the test.cpp file so the println is not working.

Do I need to include the define DEBUG in every .cpp file or can I include it in the header. Something like:

extern define DEBUG

Every compilation unit (.cpp / .c file) receives the global defines set by the -D flags in the compiler invocation and those which are themselves included by the compilation unit

The #define DEBUG in main.cpp is not visible outside of the compilation unit.

There’s multiple ways of solving the problem:

  • creating a dedicated header file like debug_settings.h in which #define DEBUG is present or commented out; then #include <debug_settings.h> in every file in which you need to react on the macros eventually present in that file; This is the most comfortable because it’s solved purely in C++ code without needing help from the build system.
  • use global build flags to invoke the compiler with the -D DEBUG flag on every compilation unit. See Redirecting...
  • you can also tell GCC to hack in an #include <your file> in every compilation process via the -include flag. See c++ - Include header files using command line option? - Stack Overflow and again build_flags to configure it for PIO. This is rather unusual in projects though.

Doesn’t exist. This is good for variables, but not the Macro-Processor hack stuff.

Thanks for the explanation. Looks like the dedicated header file will work perfectly.

I’ve got a few other config options I want to include so put them all in a config.h file and add the #include in every file.