【问题标题】:"initializer element is not constant" error in gccgcc中的“初始化元素不是常量”错误
【发布时间】:2012-06-04 10:18:43
【问题描述】:

我尝试使用 make 文件编译 C 代码。我收到以下错误:

/home/dev5/src/ermparselex.c:69: error: initializer element is not constant
/home/dev5/src/ermparselex.c:69: error: (near initialization for âyyinâ)

代码 sn-p 以及行号:

65 int yyleng; extern char yytext[];
 66 int yymorfg;
 67 extern char *yysptr, yysbuf[];
 68 int yytchar;
 69 FILE *yyin = stdin, *yyout = stdout;
 70 extern int yylineno;
 71 struct yysvf {
 72         struct yywork *yystoff;
 73         struct yysvf *yyother;
 74         int *yystops;};
 75 struct yysvf *yyestate;
 76 extern struct yysvf yysvec[], *yybgin;

stdinstdout 的值未在此代码中的任何位置定义。 我无法从谷歌获得适当的解决方案。知道为什么会发生此错误吗?

【问题讨论】:

  • 你使用的lex/flexgcc是什么版本的?
  • gcc (GCC) 4.1.2 20080704 (Red Hat 4.1.2-44),flex 版本 2.5.4
  • 您好,伊格纳西奥,感谢您的回复。我不确定你到底是什么意思。

标签: linux gcc initializer


【解决方案1】:

在 C 中,全局变量只能用常量表达式或字符串字面量来初始化,并且常量表达式的规则比 C++ 中严格得多。

stdinstdout 是指向全局对象的指针,它们不是常量(地址可能要到链接时才知道),因此您不能使用它们来初始化全局变量。

【讨论】:

    【解决方案2】:

    确保包含 stdio.h,并删除大括号:

    #include <stdio.h>
    
    FILE *yyin = stdin, *yyout = stdout;
    

    include 定义了标准输入/标准输出。

    大括号 '{}' 改变了 'stdin' 和 'stdout' 的值如何被编译器解释,不要那样做。

    【讨论】:

    • 您好 telornix,我的代码包含#include。我也试过去掉牙套。我仍然得到同样的错误。
    • 那么你错过了一个';' (分号)或第 69 行之前的一行中的内容。在您给出的内容之上再增加几行会有所帮助。
    • 我已修改问题以在第 69 行上方和下方包含代码 sn-ps
    • 显然这与“stdin”和“stdout”并不是真正的常量有关。您可能需要将 yyin 和 yyout 的值初始化为 main() 中某处或使用它们的任何地方的 stdin/stdout。将该行重写为“FILE *yyin,*yyout;”导致一切正确编译。称它为 C 的一个怪癖。如果你有真正的常量放在那里(比如 17 或 0x743,那么它会起作用)。
    猜你喜欢
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    相关资源
    最近更新 更多