Making libraries user-configurable

Greetings!

I've developed a few libraries that I believe could be useful to others, so I'm considering releasing them as free software.

My question concerns user configuration of compile-time options. I use a number of Arduino platforms, from larger Megas to the (ATtiny85-based) Digispark. In some instances, I'm willing to sacrifice functionality in order to squeeze code into a tight space.

Thus, most of my code is organized so that a few flags (implemented as a set of configuration header #define directives), e.g.

 /*
   *  MY_LIB_INCLUDE_SUPER_FUNCTION
   *  When this is defined, the library will include and use the super functions.
   *
   *  If you don't need it and want to save space, comment out the line below.
   */
#define MY_LIB_INCLUDE_SUPER_FUNCTION

control what is (or isn't) included in the final compiled library.

This works fine for me, but means:

  • You must edit the library source to set/unset the defines
  • It's annoying to use the same library in multiple sketches, as it's easy to forget config options you've set and you may have to edit the config everytime you switch projects

So my question is: how can we allow users some control over the library (at compile time) from within the sketch.

I've tried simply setting these options within the sketch, prior to the includes, but this fails: the sketch see's the stuff you've switched-on but then fails with undefined reference errors when linking.

If we had an "advanced options" to control the compilation in the Arduino IDE, I could just tell people to set -DSOME_FLAG as an argument to the compiler, but I couldn't find anything like that.

Any ideas how this can be done?

Thanks! PatD

The only way I can think of to let users set compilation options per project is for you to provide the implementation (which would usually be in a .cpp file) as a text file which the user can #include in a .cpp file of their own, so that they can put preprocessor definitions in their own .cpp file that are applied to your library implementation. I don't know how difficult this would be to achieve given the bizarre mucking about that the Arduino does with libraries and source files before it compiles everything, and it's ugly as sin, but I don't see any better options while staying with the Arduino IDE.

Can you do it like VirtualWire does, with some commands that users issue in the sketch to set the data rate, change the default pins etc.?