How to control the #define in a library? I mean...

It's hard to describe in general terms so I'll use an example:

In a library I have a buffer. Its size should be the same as the width of the lcd. I have in the .h file:

#define phi_prompt_max_item_display_length 20

In the .cpp file:

char buffer[phi_prompt_max_item_display_length];

If someone uses a 40x2 LCD, I want to define phi_prompt_max_item_display_length as 40. I want the arduino sketch to be able to override the define in .h

I tried this in .h:

#ifndef phi_prompt_max_item_display_length      ///< Only define this if it has not been defined. 
#define phi_prompt_max_item_display_length 20   ///< The render_list uses a buffer to render list item. 20 works for up to 20x4 displays to save SRAM.
#endif

I then have in arduino sketch #define phi_prompt_max_item_display_length 40 before it includes the .h
I get 40 in arduino sketch but I still get 20 in the library.

So are the define spaces separate between different .cpp files? How to do what I want to do? Thank you!

I'm not certain that you can do that given the way the Arduino build system works.

However if your library creates C++ classes, you could template the class, supplying the width of the LCD display as a template parameter.

Iain

You can add both - rows and colums - of the LCD as parameters of the constructor and malloc() the array.

Evidently all great minds run in the same ruts XD

Thank you Jack! Seems like there is no simple solution as both of us initially experimented. I gather, every .cpp compiles separately. Without a make mechanism in arduino, such as define xxx as yyy in the make file, the only way to communicate with another .cpp is at execution time. I can add another parameter to my lib initialization to take a max_item_length parameter or just dare my lib users to change this define in the .h file.

liudr:
Without a make mechanism in arduino, such as define xxx as yyy in the make file, the only way to communicate with another .cpp is at execution time.

Not so. C++ templates offer a compile time link.

Iain

Iain,

I am not familiar with the term C++ templates. I'm reading wiki and yes the concept does sound familiar after some reading. I need to read on. Would you be willing to show me a line or two pseudo code on passing a parameter to a template? Thanks.

Liudr

Does this help:

template <int length>
class Test
{
  int buffer[length];
};

void setup()
{
  Test<20> shortLine;
  Test<40> longLine;
  
  Serial.begin(115200);
  Serial.println(sizeof(shortLine));
  Serial.println(sizeof(longLine));
}

void loop()
{
}

Iain

Thanks Iain!