2017-02-23 63 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

请记住,预处理步骤完全实现了宏。当实际编译器看到代码时,所有的宏(定义和使用)都不见了。

所以,这是行不通的。