cancel
Showing results for 
Search instead for 
Did you mean: 

Preprocessor Macro calculation

federico.massimi
Associate III

Hi, I have a question about preprocessor C. When I define macros like:

#define CON_A		10
#define CON_B		5.6
#define CON_C		20.896
#define MY_MACRO	(((10* CON_A)/CON_C)*CON_B)

The last one is precalculated by the compiler or is just plain replaced as it is in the generated binary file? Let me explain better, if there are complex operations (decimal multiplications or divisions, etc etc) are these performed by the microcontroller or a MY_MACRO pre-calculated constant is replaced in the binary file?

4 REPLIES 4
Bob S
Principal

MY_MACRO will be evaluated/calculated by the compiler at compile time, and the result loaded directly into whatever variable you are assigning it to. No run-time calculation is required. That is true as long as everything in the equation is known/defined at compile time.

This is generally a misconception.

First, the preprocessor does not perform any calculation (except in #if directive, but that is not the case here). It just performs literal replacement.

According to the C standard, constant expressions *can* be evaluated compile-time, but they are *not required* to be, except if they are used in places which need a compile-time constant (e.g. in eval, or when declaring size of an array). Most compilers perform this so called constant folding, but it may depend on type of expression and optimization level. For example, the avr-gcc compiler (unrelated to STM32) famously fails when a library delay function is used with no optimization, as that function used floating point calculation to determine the number of required loops, and avr-gcc does not fold floating point constant expressions when no optimization is used.

Unfortunately, this detail is poorly documented, at least I know if no good authoritative documentation for this particular detail for the common occurrences of Cortex-M-targeted binaries of gcc. Other compilers may be better documented in this regard.

So the short answer is, usually yes, but be aware of possible exceptions.

JW

The compiler/optimizer should fold these.

Easiest way to check for one's self would be to look at a listing file, and see what the compiler generated.

I'd probably opt for consistent form here, ie 10.0

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
federico.massimi
Associate III

I'm not very experienced in these things, how can i check this "listing file" and what i have to check? I am using STM32CubeIDE to compile.