2017-02-23 27 views
2

他用大家在函數內部宏,錯誤使用C

我想在C使用這個宏:

#define CONTROL_REG(num_device) CONTROL_DEV_##num_device 

但它不工作。這是我的代碼:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <sys/types.h> 

#define CONTROL_DEV_0 0x00 /* control register for device 0 */ 
#define CONTROL_DEV_1 0x01 /* control register for device 1 */ 
#define CONTROL_DEV_2 0x02 /* control register for device 2 */ 
#define CONTROL_DEV_3 0x03 /* control register for device 3 */ 

#define CONTROL_REG(num_device) CONTROL_DEV_##num_device 

void func(int num_device) 
{ 
    printf("Value: %d\n", CONTROL_REG(num_device)); 
} 

int main(int argc, char **argv) 
{ 
    func(0); 
    func(1); 
    func(2); 
    func(3); 
} 

任何建議嗎?

此致敬禮。

+5

宏是編譯時,你試圖在運行時使用它們。 – Art

+0

好的,理解。非常感謝你。 – oscargomezf

回答

4

既然你需要值運行時的映射,使用其經陣列映射一個合適的功能:

int control_reg(int num_device) { 

    static int ret[] = { 
    CONTROL_DEV_0, 
    CONTROL_DEV_1, 
    CONTROL_DEV_2, 
    CONTROL_DEV_3, 
    }; 

    assert(num_device >= 0 && num_device <= 3); 
    return ret[num_device]; 
} 

您無法通過運行時值擴大的宏。

+0

好的,謝謝。我和仙女不在一起......對不起,這個愚蠢的問題。 – oscargomezf

2

請記住,預處理步驟完全實現了宏。當實際編譯器看到代碼時,所有的宏(定義和使用)都不見了。

所以,這是行不通的。