Reputation: 487
I am using C99 in Keil to program a microprocessor, and having difficulty using a struct to define a static const. The following compliles without issue:
static uint8_t const addr1 = 0x76;
static uint8_t const addr = addr1;
However the following does not:
typedef struct
{
uint8_t const address;
} bmp280_t;
static bmp280_t bmp280_0 = {
.address = 0x76,
};
static uint8_t const addr2 = bmp280_0.address;
The last line causes a compilation error:
......\main.c(97): error: #28: expression must have a constant value static uint8_t const addr2 = bmp280_0.address;
I have tried to replicate in visual studio, but both cases do not compile. I don't know if that is because it is compiling as cpp or using a different standard..
Upvotes: 1
Views: 367
Reputation: 24738
The initializer you are using (i.e.: bmp280_0.address
) is not a compile-time constant. You can however do the following:
#define ADDRESS 0x76
typedef struct
{
uint8_t const address;
} bmp280_t;
static bmp280_t bmp280_0 = {
.address = ADDRESS,
};
static uint8_t const addr2 = ADDRESS;
That is, define a preprocessor macro ADDRESS
which will result in the compile-time constant 0x76
when replaced by the preprocessor and use this preprocessor macro as initializer.
Upvotes: 4