0

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 {
  public:
    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 {
  public:
    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?

LukasFun
  • 295
  • 1
  • 4
  • 17

1 Answers1

0

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.

Majenko
  • 105,851
  • 5
  • 82
  • 139