2012-11-20 34 views
1

我想存儲預處理器常量的值,然後'覆蓋'它。存儲預處理器常量然後'覆蓋'通過undef /定義

我的問題:下面的代碼嘗試在變量'A'中存儲預處理器常量的值,然後代碼取消定義該變量,然後重新定義它,使其具有新值。問題是變量'A'具有新定義的值,而不是舊的值,如果這是有意義的。我可以存儲一個預處理器常量值而不是它的引用(這是什麼似乎正在發生)?

#ifdef CUSTOM_EVENT_CALLBACK_DEFINED 
    #define SUB_CUSTOM_EVENT_CALLBACK_DEFINED CUSTOM_EVENT_CALLBACK_DEFINED 
    #undef CUSTOM_EVENT_CALLBACK_DEFINED 
#endif 
#define CUSTOM_EVENT_CALLBACK_DEFINED "def" 

int main() 
{ 
    printf(CUSTOM_EVENT_CALLBACK_DEFINED);  // prints out "def". 
    printf("\n"); 
    printf(SUB_CUSTOM_EVENT_CALLBACK_DEFINED); // prints out "def". I was hoping this would be "abc" 
    printf("\n"); 

    system("PAUSE"); 
    return 0; 
} 

// Usage: where the function def is a callback function for a window in a civil engineering program that runs ontop of windows 
int def(int id, int cmd, int type) 
{ 
    #ifdef SUB_CUSTOM_EVENT_CALLBACK_DEFINED 
     SUB_CUSTOM_EVENT_CALLBACK_DEFINED(id, cmd, type); 
    #endif 

    // perform my custom code here 
} 
+0

C,C++中的宏由預處理器使用,它像文本編輯器一樣工作,它生成稍後由編譯器解析的文本。因此宏不能用於你期望的運行時間。我認爲動詞「存儲」不適用於宏,因爲在運行時沒有內存&&編譯時間與它們相關聯。 –

回答

2

簡短的回答 - 不,這是不可能的。宏不能像那樣工作。

但我懷疑你真的需要這樣做。一種解決方法,例如,將值存儲在一個變量,你覆蓋之前:

#ifdef CUSTOM_EVENT_CALLBACK_DEFINED 
    std::string SUB_CUSTOM_EVENT_CALLBACK_DEFINED = CUSTOM_EVENT_CALLBACK_DEFINED; 
    #undef CUSTOM_EVENT_CALLBACK_DEFINED 
#else 
    std::string SUB_CUSTOM_EVENT_CALLBACK_DEFINED = ""; 
#endif 

#define CUSTOM_EVENT_CALLBACK_DEFINED "def" 

int main() 
{ 
    printf(CUSTOM_EVENT_CALLBACK_DEFINED);  // prints out "def". 
    printf("\n"); 
    printf(SUB_CUSTOM_EVENT_CALLBACK_DEFINED); // prints out "def". I was hoping this would be "abc" 
    printf("\n"); 

    system("PAUSE"); 
    return 0; 
} 

或根本不使用宏用於這一目的。

+0

我不能使用字符串,因爲我實際上在.4dm中編碼不是純C類似的,但不允許在主函數或函數外使用變量 - 除了預處理器定義 –

+0

有沒有一種方法可以通過複製/存儲定義價值不參考?也許一個帶有臨時變量的冒泡排序類型方法可能是我唯一的選擇。 –

+0

@JakeM no。試想一下它是如何工作的 - 在這之後的'#define x y'處處預處理器看到'x',它將用'y'代替它 - 而不是用'y'定義。 –