2016-04-08 57 views
2

所以我的Visual Studio聲明tag1和tag2都是未定義的,但它們是cleary定義的,我不能定義基於另一個?C#定義在另一個#define錯誤

#define push    99 
#define last_instruction push 

#ifdef DEBUG 
    #define new_instr (1+last_instruction) //should be 100 
    #undef last_instruction 
    #define last_instruction new_instr //redifine to 100 if debug 
#endif 

我有一些與tag2的情況,它說定義必須是const,但它是恆定的,它是1 + 99,任何幫助,將不勝感激。

謝謝! BA

+0

請[閱讀此](http://stackoverflow.com/help/mcve)。 –

+0

您應該嘗試啓用「生成預處理文件」選項(/ P)以查看正在進行的操作。 –

+0

也許'__COUNTER__'會幫助你。 – Dani

回答

0

基礎上提供的答案我想出了一個解決方案雖然不完美最適合我的情況。

此實現可以通過兩種形式來完成:

較少變化在未來(只改變 '最後'):

#define push     99 
#define last     push 

#ifdef DEBUG 
    #define new_instr   (1+last) 
    #define last_instruction new_instr  
#else 
    #define last_instruction last 
#endif 

OR

清除代碼,但重複 '推' 中兩個地方

#define push     99 

#ifdef DEBUG 
    #define new_instr   (1+push) 
    #define last_instruction new_instr  
#else 
    #define last_instruction push 
#endif 

感謝您的幫助。

4

首先,您不能兩次定義相同的宏。如需更換宏,你首先要#undef吧:

#define tag1 99 
#ifdef DEBUG 
    #define tag2 (1+tag1) 
    #undef tag1 
    #define tag1 tag2 
#endif 

但是,這並不能解決問題。宏不是變量,您不能使用它們來存儲值以在稍後重新使用。它們是文本替換,因此它們可以並行存在。

因此新定義#define tag1 tag2擴展爲1+tag1。但在這一點上,沒有什麼叫tag1,因爲我們只是未定義它,我們還沒有重新定義它。

思考這個太多,你將會變成瘋狂的:)所以,忘掉了所有的東西,你真正想做的事是這樣的:

#define tag1_val 99 
#define tag1  tag1_val 

#ifdef DEBUG 
    #undef tag1 
    #define tag1 (tag1_val+1) 
#endif 
+0

不工作,因爲我真的需要tag2 ...電流: 的#define TAG3 99 的#define TAG1 TAG3 的#ifdef DEBUG 的#define tag_help \t \t(1 + TAG1) 的#define TAG2 \t \t \t tag_help 和#undef TAG1 的#define TAG1 \t \t tag_help #endif – Buser

+0

@BrunoMiguel這也行不通,因爲我試圖解釋的原因。現在,如果您需要tag2,只需使用我的代碼並添加'#define tag2(tag1_val + 1)' – Lundin

+0

我將編輯該問題以考慮所有變量。因爲我真正想要的是tag1基於最後一個標籤是動態的...... – Buser

1

如果你要的是整型常量少數符號名稱,您可以在一個enum這樣定義它們:

enum { 
    push = 99, 
#ifdef DEBUG 
    new_instr, 
#endif 
    last_plus_1, 
    last_instr = last_plus_1 - 1 
}; 

new_instr將是100(如果定義DEBUG),last_plus_1將是要麼101(如果定義了DEBUG)或100(如果DEBUG未定義),並且last_instr將小於last_plus_1