1

I'm trying to write a generic "Test Bench" type of sketch using booleans to indicate whether or not to include specific libraries. After those are defined, I'm attempting to use preprocessor #if statements to determine if the libraries need to be included and create the objects if need be.

Example:

const bool useLCD = true;

...

#if (useLCD)
  #include "NHD_4x20.h"
  NHD_4x20 lcd(9);
#endif

These statements are before the setup() and loop() functions. This in itself doesn't generate compiler errors, however I get "lcd has not been defined in this scope" when trying to use the object in the setup() and loop() functions.

Is there some simple trick to accomplish this that I'm overlooking here ?

Thanks in advance !

1
  • Please take also note before version 1.6.6/1.6.7 preprocessor conditionals were very sketchy.
    – mirh
    Feb 3, 2022 at 19:44

1 Answer 1

3
const bool useLCD = true;

should be:

#define useLCD 1

Here is a complete working example of how to use preprocessor macros for conditional compilation:

#define USE_A 1
// #define USE_B 1

#if (USE_A)
int a = 4;
#endif

#if (USE_B)
int b = 6;
#endif

void setup() {
    Serial.begin(115200);
    Serial.print(F("The result is: "));
#if (USE_A)
    Serial.println(a * 2);
#endif
#if (USE_B)
    Serial.println(b * 2);
#endif
}

void loop() {
}
3
  • Thanks, Majenko. Just tried it... Same "has not been defined" error. Feb 6, 2017 at 18:46
  • Sorry, Manjenko ! Had a typo !! Worked !! Thanks a lot !! Feb 6, 2017 at 18:50
  • That's OK then :) I just posted an example as well.
    – Majenko
    Feb 6, 2017 at 18:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.