I'm a trying to migrate some legacy C code for Embedded targets to C++ for compatibility issues and I am encountering some issues with unions in C++.
in our project we have the following style of union to reduce the amount of RAM usage:
typedef union unionTest
{
struct
{ uint32_t nField1:5
; uint32_t nField2:4
; uint32_t nField3:23
;}
; uint32_t nRaw ///< Raw data
;} unionTest;
// A global variable for configuration
unionTest myCUnion = {.nField1 = 1, .nField2 = 2, .nField3 = 3 };
This works well, is easy to use and the compiler initializes the bit fields at the correct values at compile time
Then when converting to C++
typedef union unionTest
{
struct
{ uint32_t nField1:5
; uint32_t nField2:4
; uint32_t nField3:23
;}
; uint32_t nRaw ///< Raw data
;} unionTest;
// Using const saves RAM, one of the reason to switch to C++
const unionTest myCppUnion = {.nField1 = 1, .nField2 = 2, .nField3 = 3 }; // Error
does not work anymore, I have a "too many initializers" error. Is there anyway to keep the C behavior. I know that anonymous structures are prohibited by ISO C++ but changing this has a huge impact on the code base, and was not judged important for now.
And I also tried with a named struct
typedef union unionTest
{
struct notAnonymous
{ uint32_t nField1:5
; uint32_t nField2:4
; uint32_t nField3:23
;} notAnonymous
; uint32_t nRaw ///< Raw data
;} unionTest;
// Using const saves RAM, one of the reason to switch to C++
const unionTest myCppUnion2 = {.notAnonymous.nField1 = 1, .notAnonymous.nField2 = 2, .notAnonymous.nField3 = 3 }; // expected primary-expression before '.' error
const unionTest myCppUnion3 = { .notAnonymous = { .nField1 = 1, .nField2 = 2, .nField3 = 3 } }; // Compiles
and I can't find a solution that keeps the original C behavior.
I have not yet tested if the solution "myCppUnion3" fills the bitfields correctly, but I a m more interested by finding a solution/workaround for solution "myCppUnion"
If anyone has any leads I'll glady take them !