TrivialCase
TrivialCase

Reputation: 1099

Building a static array at compile time

I have a few large static arrays that are used in a resource constrained embedded system (small microcontroller, bare metal). These are occasionally added to over the course of the project, but all follow that same mathematical formula for population. I could just make a Python script to generate a new header with the needed arrays before compilation, but it would be nicer to have it happen in the pre-processor like you might do with template meta-programming in C++. Is there any relatively easy way to do this in C? I've seen ways to get control structures like while loops using just the pre-processor, but that seems a bit unnatural to me.

Here is an example of once such map, an approximation to arctan, in Python, where the parameter a is used to determine the length and values of the array, and is currently run at a variety of values from about 100 to about 2^14:

def make_array(a):
    output = []
    for x in range(a):
        val = round(a * ((x / a)**2 / (2 * (x / a)**2 - 2 * (x / a) + 1)))
        output.append(val)
    return output

Upvotes: 3

Views: 466

Answers (1)

KamilCuk
KamilCuk

Reputation: 141493

Is there any relatively easy way to do this in C?

No.

Stick to a Python script and incorporate it inside your build system. It is normal to generate C code using other scripts. This will be strongly relatively easier than a million lines of C code.

Take a look at M4 or Jinja2 (or PHP) - these macro processors allow sharing code with C source in the same file.

Upvotes: 2

Related Questions