When creating an array like in the sketch

#include <Lib.h>

int myArray[Lib::len];

void setup() {}

void loop() {}

the variable len must be an integer constant that is known at compile time. Like shown in the sektch, I want to put the length of the array into a library and get it from there. The problem is that for this to work, you have to initialize the constant already in the .h file, which is against proper library standards. This is how you would do this (.h file of the library):

class Lib {
    static const int len = 4;

The .cpp file doesn't even have to contain anything in this case. The proper way to do things in a library would be like this though:

The .h file:

class Lib {
    static const int len;

The .cpp file:

#include "Lib.h"

const int Lib::num = 4;

But if done like this, len doen't have a value at compile time since the sketch only includes the .h file and not the .cpp file.

Is there any way to intitialize an array in a sketch with its length coming from a library while maintaining proper library design?

  • 2
    Header files are there to define stuff that is used by the library functions as well as by the consumer code. So if both need access to the length variable, why should it be improper library design to define the length in the header file? For example all information of MCU registers and their name to number mapping are declared in headers. – Peter Paul Kiefer Nov 11 '19 at 16:34

There is absolutely nothing wrong with putting it in the header.

§9.4.2/4 If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a name- space scope if it is used in the program and the namespace scope definition shall not contain an initializer.

Since you're just using it as a simple constant "integral" value there is nothing wrong with putting it in the header.

| improve this answer | |
  • So the answer is "Just do it this way, even though the initialization is not in the .cpp file as with everything else"? Or is there any other way? – LukasFun Nov 11 '19 at 16:34
  • 1
    The answer is "Just do it this way since this is the right way to do it as you have a static const integral type" – Majenko Nov 11 '19 at 16:41
  • @LukasFun You can define a constant in the header and use this to initialize the static member in the cpp File. You can also use this constant in the sketch at compile time. But that would be a worse solution (IMHO at least). – Peter Paul Kiefer Nov 11 '19 at 16:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.