【问题标题】:Error using macros inside functions in C在 C 中的函数内部使用宏时出错
【发布时间】:2017-02-23 11:24:21
【问题描述】:

大家好,

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

有什么建议吗?

最好的问候。

【问题讨论】:

  • 宏是编译时,你试图在运行时使用它们。
  • 好的,明白了。非常感谢。

标签: c compiler-errors macros


【解决方案1】:

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

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

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

【讨论】:

  • 好的,谢谢。我和仙女一起去了......对不起这个愚蠢的问题。
【解决方案2】:

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

所以,这永远行不通。

【讨论】:

    猜你喜欢
    • 2016-03-15
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    相关资源
    最近更新 更多