Constants shared from sketch to library

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!!

Daniel.

A #define XYZ before the include and a #ifdef in the library code should work. Quick test:

#define XYZ 3

#include <test.h>

void setup()
{
  Serial.begin(115200);
  Serial.print(f());
}

void loop(){}

and a test.h

// test.h
#ifdef XYZ
int f() 
{
  return XYZ;
}
#else
int f()
{
  return -1;
}
#endif

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:

test.h (library)

#ifdef SKETCHDEF
#define LOCALDEF   SKETCHDEF
#else
#define LOCALDEF   0
#endif

test.cpp (library)

#include "test.h"

int test(void)
{
  return LOCALDEF;
};

mysketch.pdw

# define SKETCHDEF  3
#include "test.h"

void setup()
{
  Serial.begin(9600);
  Serial.flush();

  int res = test();
  Serial.print("test = ");
  Serial.println(res, DEC);
}

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!

I suspect

# define

is different to

#define

not least because the first doesn't do what you expect!

(I think)

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.

More clear?

Thanks, that's what I guessed, hence my initial post. Anyway, this is just a suggestion for future revisions.

Daniel.