【问题标题】:Undeclared (first use in this function) in C Macro在 C 宏中未声明(在此函数中首次使用)
【发布时间】:2020-11-24 08:29:59
【问题描述】:
#define CREDITS_COURSE1 4
#define CREDITS_COURSE2 5
#define CREDITS_COURSE3 4
#define CREDITS_COURSE4 4
#define CREDITS_COURSE5 3
#define CREDITS_COURSE6 3
#define CREDITS_COURSE7 2
#define CREDITS_COURSE8 3

#define COURSE(number) CREDITS_COURSE##number

int main()
{   for(int i=1;i<9;i++)
    printf("%d\n",COURSE(i));
}

我希望它打印定义的相应值 但它却显示错误

 error: 'CREDITS_COURSEi' undeclared (first use in this function); did you mean 'CREDITS_COURSE1'?
   10 | #define COURSE(number) CREDITS_COURSE##number
      |                        ^~~~~~~~~~~~~~
cc.c:14:19: note: in expansion of macro 'COURSE'
   14 |     printf("%d\n",COURSE(i));
      |                   ^~~~~~
cc.c:10:24: note: each undeclared identifier is reported only once for each function it appears in
   10 | #define COURSE(number) CREDITS_COURSE##number
      |                        ^~~~~~~~~~~~~~
cc.c:14:19: note: in expansion of macro 'COURSE'
   14 |     printf("%d\n",COURSE(i));
      |                   ^~~~~~

那你能帮我解答一下吗

举例

COURSE(1) 应该把我打印出来 4

COURSE(2) 应该把我打印出来 5

【问题讨论】:

  • 您不能将运行时值传递给编译时预处理器。你必须以不同的方式重新设计这个程序。您试图用这些宏解决的实际问题是什么?为什么不能使用枚举?

标签: c c-preprocessor


【解决方案1】:

你绝对不能在运行时调用动态变量名。而且绝对不能用宏来做到这一点。

您可以改为将数组声明为 const 以使其不可变:

const int CREDITS_COURSE[8] = {4, 5, 4, 4, 3, 3, 2, 3};

或者使用enumeration

enum {
    course_1 = 4,
    course_2 = 5,
    course_3 = 4,
    course_4 = 4,
    course_5 = 3,
    course_6 = 3,
    course_7 = 2,
    course_8 = 3
} CREDITS_COURSE;

【讨论】:

    【解决方案2】:

    错误在第 10 行
    #define COURSE(number) CREDITS_COURSE##number
    你不能使用这个声明

    不能像这样在循环内的运行时调用宏。您可以声明一个常量数组并初始化所有元素

    const int credits_course[8] = {4, 5, 4, 4, 3, 3, 2, 3};

    这里是 C 代码:

    #include<stdio.h>    
    
    const int credits_course[8] = {4, 5, 4, 4, 3, 3, 2, 3};
    
    int main()
    {   for(int i=0;i<8;i++)
        printf("%d\n",credits_course[i]);
        
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-19
      • 2014-04-22
      • 2012-05-07
      • 2012-07-13
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多