[英]Anonymous struct inside union in C
我正在使用 Microchip 的 XC32 為 ATSAM 設備編寫代碼(我不清楚是 C99 還是 C11)。
此代碼工作正常:
typedef union {
struct {
uint16_t bit1 : 1;
uint16_t bit2 : 1;
// .. MUCH more lines...
};
struct {
uint32_t data[N];
// ... more lines, with sub-structures....
};
} Context_t;
Context_t c;
c.data[0] = 1;
c.bit2 = false;
注意兩個匿名結構。
由於這兩個結構都很大,一直在變化,而且它們的代碼是由其他腳本自動生成的,所以這樣使用它們會更方便:
// bit.h
typedef struct {
uint16_t bit1 : 1;
uint16_t bit2 : 1;
// .. MUCH more items...
} Bits_t;
// data.h
typedef struct {
uint32_t data[N];
// ... more code...
} Data_t;
// import both headers
typedef union {
Bits_t;
Data_t;
} Context_t;
Context_t c;
c.data[0] = 1;
c.bit2 = false;
這無法通過編譯器構建, declaration does not declare anything
。 這對我來說聽起來很公平。
如果我像下面這樣命名它們,它會起作用,但最終代碼將被迫意識到結構上的這種變化。 不利於我們的應用。
typedef union {
Bits_t b;
Data_t d;
} Context_t;
Context_t c;
c.d.data[0] = 1;
c.b.bit2 = false;
我假設我是這里的罪魁禍首,失敗的例子是由於我以錯誤的方式宣布聯合而失敗的。
歡迎任何提示!
您可以利用包含文件本質上被復制並粘貼到包含它們的源文件中的事實來執行您想要的操作。
如果你有 bit.h 只包含這個:
struct {
uint16_t bit1 : 1;
uint16_t bit2 : 1;
// .. MUCH more items...
};
而 data.h 只有這個:
struct {
uint32_t data[N];
// ... more code...
};
然后你可以像這樣創建你的聯合:
typedef union {
#include "bits.h"
#include "data.h"
} Context_t;
允許這兩個內部結構既是匿名的又是在外部生成的,而不必觸及定義Context_t
的模塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.