簡體   English   中英

C 宏動態擴展

[英]C MACRO expansion dynamically

我正在嘗試類似於遵循遺留代碼的東西

//為平台 1 定義宏

#define PLATFORM_1_ENTRY_L2PT    10
#define PLATFORM_1_ENTRY_L3PT    11
#define PLATFORM_1_ENTRY_L4PT    12
#define PLATFORM_1_ENTRY_L5PT    13

//為平台 2 定義宏

#define PLATFORM_2_ENTRY_L2PT    20
#define PLATFORM_2_ENTRY_L3PT    21
#define PLATFORM_2_ENTRY_L4PT    22
#define PLATFORM_2_ENTRY_L5PT    23

//為默認平台定義宏

#define DEFAULT_PLATFORM_ENTRY_L2PT    30
#define DEFAULT_PLATFORM_ENTRY_L3PT    31
#define DEFAULT_PLATFORM_ENTRY_L4PT    32
#define DEFAULT_PLATFORM_ENTRY_L5PT    33

//獲取基於“動態”平台類型的偏移量

#define GET_OFFSET(entry_type)   ({                                          \
     (global.platform_1) ?                                                   \
         PLATFORM_1_ENTRY_##entry_type :                                     \
         (global.platform_2) ?                                               \
              PLATFORM_2_ENTRY_##entry_type :                                \
              DEFAULT_PLATFORM_ENTRY_##entry_type)                           \
     })  

//使用下面的宏擴展根據平台類型進行擴展

#define ENTRY_L2PT                                       GET_OFFSET(L2PT)
#define ENTRY_L3PT                                       GET_OFFSET(L3PT)
#define ENTRY_L4PT                                       GET_OFFSET(L4PT)
#define ENTRY_L5PT                                       GET_OFFSET(L5PT)

//定義全局結構

struct global_ {
    bool platform_1;
    bool platform_2;
} glbl;

glbl global = {0};

//從示例主調用


void main() {
    //set offset 
    int array[40] = {0};
    ...
    if(sizeof (void *) * CHARBIT == 64) {
        global.platform_1 = 1;
    } else {
        global.platform_2 = 1;
    }
    array[ENTRY_L2PT]++;
    array[ENTRY_L3PT]++;
    array[ENTRY_L4PT]++;
    array[ENTRY_L5PT]++;
    ...
}

** 我在編譯期間收到以下錯誤:**

At top level:
error: braced-group within expression allowed only inside a function
#define GET_OFFSET(entry_type)   ({                                        \
                                  ^
note: in expansion of macro ‘GET_OFFSET’
#define ENTRY_L2PT                GET_OFFSET(L2PT)
                                             ^
note: in expansion of macro ‘ENTRY_L2PT’
        array[ENTRY_L2PT]++;

我該如何進行上述工作?

請注意,在代碼中使用 ENTRY_L2PT 的地方有很多,並且在開發/測試/回歸等方面都需要付出很多努力。

錯誤消息告訴您錯誤的原因:

error: braced-group within expression allowed only inside a function
#define GET_OFFSET(entry_type)   ({                                        \
                                  ^

您不能在表達式中聲明 scope。 GET_OFFSET宏中刪除大括號{}

我該如何進行上述工作?

表達式內的括號組僅允許在 function 內

不要使用大括號組。

#define GET_OFFSET(entry_type)   ( \
     .... \
     .... \
     )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM