cancel
Showing results for 
Search instead for 
Did you mean: 

Why does the simple code: const int BIT = 12; const int BITon = 0x1<<BIT; give me this: "error: initializer element is not constant"?

GLero
Associate II
 
4 REPLIES 4
Pavel A.
Evangelist III

For gcc compiler what you have is not a constant, it is expression. C++ accepts this.

Clang accepts this even in C mode.

-- pa

GLero
Associate II

So how do I do this?

This is my first project using C and STM32. I am trying to learn the basics before actually using Cube/FreeRTOS. I am trying to create a definition header file that I tweak a few up front parameters based on what hardware I choose to use, and these definitions set everything up for me.

Piranha
Chief II
#define BIT 12u
#define BITon (0x1ul << BIT)

Usually in C bits are defined as preprocessor defines. Look for example:

https://github.com/STMicroelectronics/STM32CubeG4/blob/master/Drivers/CMSIS/Device/ST/STM32G4xx/Include/stm32g431xx.h

P.S. I hope You are not redefining MCU registers and their bits...

GLero
Associate II

CAVEAT: Yes, I am redefining the wheel. I am trying to learn the basics before taking advantage of what others have already done. This is my "Hello" project.

Actually it does accept expressions. This compiles:

const int VAL = (0x123456 & (~(0x3<<12))) | (0x1<<12);

but if I put a predefined non-zero constant expression in it, it does not. (0x0<<BIT works, 0x1<<BIT does not)

Not all of the definitions I like to use are defined in the STM32 headers. Bit position isn't, an explicit bit on, bit off, single bit field mask is not:

#define BD(DEV,REG,BIT,POS) \

const uint32_t DEV ## _ ## REG ## _ ## BIT ## _P = POS ; \

const uint32_t DEV ## _ ## REG ## _ ## BIT ## _Off = 0x0 << POS ; \

const uint32_t DEV ## _ ## REG ## _ ## BIT ## _On = 0x1 << POS ; \

const uint32_t DEV ## _ ## REG ## _ ## BIT ## _M = ~(0x1 << POS )

BD(RCC,CR,HSEON,16);

BD(RCC,CR,HSERDY,17);

And I don't like using time typing long expressions. I seem to be using the following expression a lot. I would like to turn it into a macro but can't:

RCC->CFGR = (RCC->CFGR & (~RCC_CFGR_PLLMULL_Msk)) | RCC_CFGR_PLLMULL9;

Note I am looking for inline macro expansion versus function calls because of the function call overhead.