I'd like to initialise a variable from a structure of a different type.
This works fine, if I do this inside a function, but gives error initializer element is not constant
if the variable is defined outside a function. I am using gcc.
Example code:
#include <stdio.h>
#include <stdbool.h>
#include <stdint.h>
typedef struct
{
uint8_t enable : 1;
uint8_t aboveLevel : 1;
uint8_t isReceiving : 1;
uint8_t output : 5;
} busy_settings_t;
#define INITVAR1 *((uint8_t *) (& \
(busy_settings_t const[]) \
{ \
{ \
.enable = 0, \
.aboveLevel = 1, \
.isReceiving = 0, \
.output = 1, \
}, \
} \
))
uint8_t testfn1(void)
{
uint8_t test = INITVAR1;
return (test);
}
#if (0)
uint8_t testvar1 = INITVAR1;
#else
uint8_t testvar1 = 0xff;
#endif
int main(int argc, char * argv[])
{
printf("testfn1:%02x\n", testfn1());
printf("testvar1:%02x\n", testvar1);
return (0);
}
In function testfn1
, I can initialise a variable from an anonymous structure.
But it doesn't work if I initialise a global variable. Replace #if (0)
with #if (1)
to see the error.
$ gcc --version
gcc (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0
$ gcc cast_struct_init.c -o csi && ./csi
testfn1:0a
testvar1:ff
Error:
$ gcc cast_struct_init.c -o csi && ./csi
cast_struct_init.c:13:22: error: initializer element is not constant
#define INITVAR1 *((uint8_t *) (& \
^
cast_struct_init.c:32:24: note: in expansion of macro ‘INITVAR1’
uint8_t testvar1 = INITVAR1;
^~~~~~~~
How can I make this work?