【问题标题】:#define create a warning while compiling [duplicate]#define 在编译时创建警告[重复]
【发布时间】:2015-05-03 15:21:06
【问题描述】:

我试图编写如下代码:

头文件中:test.h

#define size_aspid 8
 const char replace_aspid[20];
 void print_max_length();

在 test.c 文件中:

const char replace_aspid[] = "replace_aspidiii";

int max_size = size_aspid+strlen(replace_aspid);
void print_max_lenght()
{
       printf("Max length is: %d\n",max_size);
}

在 main.c 文件中:

  int main()
   {
      print_max_length();
      return 0;
   }

然后编译器会说:

warning: initializer element is not a constant expression
#define size_aspid 8
note: in expansion of macro ‘size_aspid’
int max_size       = size_aspid+strlen(replace_aspid);

我哪里出错了。谢谢!!!!!!!!!!!!!

【问题讨论】:

    标签: c linux gcc


    【解决方案1】:

    在文件范围内声明的变量的初始化程序必须是常量表达式。函数调用(在您的情况下为 strlen)绝不是 C 中的常量表达式。

    你可以替换:

    int max_size = size_aspid+strlen(replace_aspid);
    

    int max_size = size_aspid + (sizeof replace_aspid - 1);
    

    sizeof 是一个运算符而不是一个函数,这里是一个常量表达式。

    【讨论】:

    • 1+(至少)用于指向-1! :-}
    【解决方案2】:

    假设int max_size是全局定义的,你不能使用函数来初始化它。

    strlen(replace_aspid)
    

    不是常数,至少在 C 的上下文中不是。

    要解决这个问题,请使用

    (sizeof replace_aspid - 1) /* Thanks to ouah for the -1! :-) */
    

    相反。它在编译时进行评估,编译器将其视为常量。

    【讨论】:

      猜你喜欢
      • 2020-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      相关资源
      最近更新 更多