Initialize a variable statically (at compile time)

1) I have many constants in my C algo. 2) my code works both with a floating point and with a fixed point.

Right now, these constants are initialized by the float2fixed function, in which it does nothing at a floating point, but finds its representation with a fixed point at a fixed point. For example, 0.5f remains equal to 0.5f if it works with a floating point, while it uses the pow () procedure and becomes 32768 if it works at a fixed point, and the fixed-point representation is Qx.16.

This is easy to maintain, but it takes a long time to calculate these constants at a fixed point (pow is a floating-point function). In C ++, I would use some metaprogramming, so the compiler calculates these values โ€‹โ€‹at compile time, so there is no hit at run time. But in C, this is not possible. Or that? Does anyone know such a trick? Is any compiler smart enough for this?

Waiting for any answers.

A

+3
source share
4 answers

Instead of using (unsigned)(x*pow(2,16))to convert your fixed point, write it as(unsigned)(0.5f * (1 << 16))

, .

+4

, , , .

, const, , , , , .


, , :

const double somename = 3.14159;

:

const fixedpoint_t somename = { ...whatever is needed... };

, - , , .

datafile.c:   datafile.constants converter
        converter datafile.constants > datafile.c
+2

GCC ( 4.3) GMP MPFR , . .

, , , , , . , , .

+1

C, . - , . , , (.. pow() , ).

, :

  • . , , , , ..

  • , ++. C (, ) ++.

, , , . .

0
source

Source: https://habr.com/ru/post/1710208/


All Articles