gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:36:29 24 4
gpt4 key购买 nike

大家好

我正在尝试在 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);
}

有什么建议吗?

最好的问候。

最佳答案

由于您需要对值进行运行时映射,因此请使用通过数组进行映射的适当函数:

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

您不能通过运行时值扩展宏。

关于c - 在 C 中的函数内部使用宏时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42414402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com