It would be nice if we could use in libraries constants and definitions declared in the sketches. This would let us, among other features:
- Conditionally compile libraries according to user definitions in the sketches.
- Use constant values in libraries that have been defined in the sketches.
Thanks for keeping the good work!!
A #define XYZ before the include and a #ifdef in the library code should work. Quick test:
#define XYZ 3
and a test.h
output is depending on the #define XYZ so it worked (if not defined output = -1 else XYZ)
with #defines you kan define constants of all types - int, float string boolean or even complex macros
It's odd that you example works but the following doesn't:
#define LOCALDEF SKETCHDEF
#define LOCALDEF 0
# define SKETCHDEF 3
int res = test();
Serial.print("test = ");
Running "test" from my sketch always returns 0. On the other hand, if I define the body of the test function in test.h instead of test.cpp the above example works. I'm a bit confused.
is different to
not least because the first doesn't do what you expect!
Yeah, it was a typo. The original code did contain "#define"
Running "test" from my sketch always returns 0. On the other hand, if I define the body of the test function in test.h instead of test.cpp the above example works. I'm a bit confused. Thanks again!
The .cpp file is not merged on source level with your sketch, it compiles to an .o file and get linked. It can only relate to things included.
The .h file on the other hand is merged with the source file (to be able to reference the .o file) so #defines will be visible for the preprocessor and will be taken into account when compiling.
AFAIK the solution to your problem is to define a "myconstants.h" file that is included [u]both[/u] in your sketch and in the library.
Thanks, that's what I guessed, hence my initial post. Anyway, this is just a suggestion for future revisions.