簡體   English   中英

C 預處理器 push_macro/pop_macro 並在兩者之間強制擴展

[英]C preprocessor push_macro/pop_macro and forcing expansion in between

我有一個宏,稱之為FOO ,我試圖僅在我的 header 文件中覆蓋它。 我正在嘗試在 Visual Studio 中執行 push_macro/pop_macro。 問題是因為我試圖覆蓋的宏被用作另一個宏BAR的一部分,沒有使用替換FOO 例如:

#define FOO(x) printf("You're in the regular FOO. %s", x);

// These next few lines would be in an include file.
#pragma push_macro("FOO")
#undef FOO
#define FOO(x) printf("You're in the replacement FOO. %s", x);
#define BAR(x) FOO(x)
#pragma pop_macro("FOO")

int main(int argc, char *argv[]) {
    BAR("test");
    return 0;
}

該代碼打印:

你在常規的 FOO 中。 測試

代碼比這復雜得多,我為了示例保持簡單。 包含文件中有多個替換 FOO,所以我不能只將 FOO 的內容放在 BAR 中。

在通過 pop_macro 恢復宏之前,有沒有辦法在包含文件中強制擴展 FOO? 我可以做一個選擇性的額外通行證或類似的東西嗎?

我找到了一個部分解決方案(或者更確切地說只是糟糕的解決方法)。 您可以使用原始和替換 FOO 的交替定義來填充宏堆棧。 然后每次調用 BAR 都會首先彈出一個 FOO,使用 FOO,然后彈出另一個 FOO。 因此,每次調用 BAR 都會消耗 FOO 堆棧中的兩個元素。 不幸的是,我還沒有找到恢復元素的方法,因為您不能在另一個#define #define 因此,在此解決方法中, BAR的使用次數只能與您硬編碼的FOO堆棧的大小相對應:

#include <iostream>

#define FOO(x) printf("You're in the regular FOO. %s", x);
#define FOO_MY(x) printf("You're in the replacement FOO. %s", x);

// These next few lines would be in an include file.
#define FOO_CALL(x) FOO(x)
#pragma push_macro("FOO_CALL")
#undef FOO_CALL
#define FOO_CALL(x) FOO_MY(x)
#pragma push_macro("FOO_CALL")
#undef FOO_CALL
#define FOO_CALL(x) FOO(x)
#pragma push_macro("FOO_CALL")
#undef FOO_CALL
#define FOO_CALL(x) FOO_MY(x)
#pragma push_macro("FOO_CALL")
#undef FOO_CALL
#define FOO_CALL(x) FOO(x)
#pragma push_macro("FOO_CALL")
#undef FOO_CALL
#define FOO_CALL(x) FOO_MY(x)
#pragma push_macro("FOO_CALL")
#undef FOO_CALL
#define FOO_CALL(x) FOO(x)

#define BAR(x) \
        _Pragma("pop_macro(\"FOO_CALL\")") \
        FOO_CALL(x) \
        _Pragma("pop_macro(\"FOO_CALL\")")

int main(int argc, char *argv[]) {
    FOO("test\n");
    BAR("test\n");
    FOO("test\n");
    BAR("test\n");
    FOO("test\n");
    BAR("test\n");
    FOO("test\n");
    BAR("test\n");
    FOO("test\n");
    BAR("test\n");
    FOO("test\n");
    return 0;
}

output 是:

You're in the regular FOO. test
You're in the replacement FOO. test
You're in the regular FOO. test
You're in the replacement FOO. test
You're in the regular FOO. test
You're in the replacement FOO. test
You're in the regular FOO. test
You're in the regular FOO. test
You're in the regular FOO. test
You're in the regular FOO. test
You're in the regular FOO. test

暫無
暫無

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

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