Calculating variables at compile time

It turns out it can be done, with a bit of a pre-processing trick.

Add a .h file to your project (new tab in the top RH corner) like this:

myTable.h

#if __COUNTER__ == 0
    const float myTable [ENTRIES] = {
    #include "myTable.h"
#elif __COUNTER__ < (ENTRIES * 3)
   FUNC((__COUNTER__ / 3) - 1),
    #include "myTable.h"
#else
    };  // end of myTable
#endif

This rather obscure file calls itself recursively to generate the table (calling FUNC for each entry).

Now the main file:

#define ENTRIES 128

const float AccumMax = 3;
const float aFreq = 1.2;
const float lowA = 16;
const float samplingfrequency = 1000;

#define FUNC(x) AccumMax * ((pow( aFreq, x-21 ) * lowA)/samplingfrequency)

#include "myTable.h"
 
void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  Serial.println ("Starting.");
  
  for (int i = 0; i < ENTRIES; i++)
    Serial.println (myTable [i], 4);
  }  // end of setup

void loop () { }

This uses a compiler feature, the COUNTER symbol, which the compiler adds one to, each time it is used. When it is zero, the include file creates a table. Then it recurses, and for each recursion (up to ENTRIES) it generates another table line. Then when the limit is reached it finishes off the table.

In this line:

   FUNC((__COUNTER__ / 3) - 1),

We divide by 3 because COUNTER appears 3 times in the include file, and thus goes up by 3 each time. And by the time it is used we have 3 / 3 which is 1, so to get back to a zero-relative argument we have to subtract one.


Now I'm not necessarily recommending this because for one thing it is obscure, and for another, for a larger table the compiler eventually complains:

myTable.h:6:25: error: #include nested too deeply