简体   繁体   English

在C中的函数内部使用宏时出错

[英]Error using macros inside functions in C

He everyone, 他大家

I'm trying to use this macro in c: 我正在尝试在c中使用此宏:

#define CONTROL_REG(num_device) CONTROL_DEV_##num_device

But it doesn't work. 但这是行不通的。 This is my code: 这是我的代码:

#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);
}

Any suggestion? 有什么建议吗?

Best regards. 最好的祝福。

Since you require a run-time mapping for values, use a proper function that maps via an array: 由于您需要对值进行运行时映射,因此请使用通过数组映射的适当函数:

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];
}

You can't expand a macro by a run-time value. 您不能通过运行时值扩展宏。

Please remember that macros are completely implemented by the preprocessing step. 请记住,宏是通过预处理步骤完全实现的。 When the actual compiler sees the code, all macros (definitions and uses) are gone. 当实际的编译器看到该代码时,所有宏(定义和使用)都消失了。

So, this can never work. 因此,这永远都行不通。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM