Preprocessor directives for including libraries

my sketch needs to compile with different libraries depending on a variable.

in main.ino

...
#define VARIABLE
#ifdef VARIABLE
#include <one.h>
#else
#include <two.h>
#endif

#include <library.h>
...

this works perfectly fine, it compiles with library "one" when VARIABLE is defined, and "two" when not.

however i have a third library "library" in which the same needs to happen, since this library references functions and variables from either of the previous libraries.

in library.h

...
#ifdef VARIABLE
#include <one.h>
#else
#include <two.h>
#endif
...

does not work, compiler seems to ignore the def of VARIABLE in here. as i understand, this is well known shortcoming of the arduino ide.

however i cannot figure out an effective way to solve this problem. i thought of just duplicating "library" into two different ones such that i could

...
#define VARIABLE
#ifdef VARIABLE
#include <one.h>
#include <library1.h>
#else
#include <two.h>
#include <library2.h>
#endif
...

however my library is pretty long, and it would be pretty sad to create a copy just to change one line of code. anyone know of a solution or workaround that i dont?

thanks. :slight_smile:

That makes sense to me. It will probably not work in a *.cpp or *.h file, but only in the main *.ino file. That is where the libraries are included (or not).
I don't know a way around that. I hope someone else knows.

About your third library, could you not make a library and include it in the *.ino file with #include <thirdlib.cpp> ? Could you make your own prototyping and let the linker sort it out ?

"this is well known shortcoming of the arduino ide." - Everyone wants to blame the IDE without taking the time to understand WHY it works like that.....

That is a not a "limitation" of the IDE. In fact, it has nothing whatsoever to do with the IDE. Libraries are compiled ON THEIR OWN. They do NOT get compiled along with the sketch, and only "meet" the .ino file at link time. So #defines in the .ino file are NOT visible to the library when it gets compiled. That is c/c++ convention, and has nothing whatsoever to do with Arduino or the IDE.

Your best option is probably to use the compiler -D option to define the required symbol at compile-time. Or, put the #define into a separate .h file that is included by both the .ino and the library.

Regards,
Ray L.

1 Like

thanks guys :slight_smile:

i was under the impression that the compiler was supposed to link together defines somehow, but now that actually makes a lot more sense. i'll try out those other options.

but, is there a way to "concatenate" library files during compile, the same way the IDE does with sketch files with multiple tabs?

I was going to ask How did you got conditional includes to work in your sketch, then I saw that this bug was fixed few months ago, nice!