我正在尝试将嵌入式目标的一些遗留 C 代码迁移到 C++ 以解决兼容性问题,并且我在 C++ 中遇到了一些联合问题。
在我们的项目中,我们采用以下联合样式来减少 RAM 使用量:
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 };
Run Code Online (Sandbox Code Playgroud)
这很有效,易于使用,并且编译器在编译时以正确的值初始化位字段
然后在转换为 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
Run Code Online (Sandbox Code Playgroud)
不再工作,我有一个“太多的初始化程序”错误。无论如何要保持C行为。我知道 ISO C++ 禁止匿名结构,但改变这一点会对代码库产生巨大影响,目前并不重要。
而且我还尝试使用命名结构
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
Run Code Online (Sandbox Code Playgroud)
我找不到保留原始 C 行为的解决方案。
我还没有测试解决方案“myCppUnion3”是否正确填充了位域,但我更感兴趣的是找到解决方案“myCppUnion”的解决方案/解决方法
如果有人有任何线索,我很乐意接受他们!
在 C++ 中,您需要一组额外的大括号来反映初始化程序位于子结构中:
const unionTest myCppUnion = { {.nField1 = 1, .nField2 = 2, .nField3 = 3 } };
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
141 次 |
| 最近记录: |