函数'yylex':'变量'未声明
我正在与词法分析。为此,我使用Flex
并提取以下问题。函数'yylex':'变量'未声明
work.l
int cnt = 0,num_lines=0,num_chars=0; // Problem here.
%%
[" "]+[a-zA-Z0-9]+ {++cnt;}
\n {++num_lines; ++num_chars;}
. {++num_chars;}
%%
int yywrap()
{
return 1;
}
int main()
{ yyin = freopen("in.txt", "r", stdin);
yylex();
printf("%d %d %d\n", cnt, num_lines,num_chars);
return 0;
}
然后,我用下面的命令,它正常工作,创造lex.yy.c
。
Rezwans的iMac:laqb-2 rezwan $弯曲work.l
然后,我用下面的命令。
Rezwans的iMac:laqb-2 rezwan $ GCC的lex.yy.c -Ob
并获得以下error
:
work.l: In function ‘yylex’:
work.l:3:4: error: ‘cnt’ undeclared (first use in this function); did you mean int’?
[" "]+[a-zA-Z0-9]+ {++cnt;}
^~~
int
work.l:3:4: note: each undeclared identifier is reported only once for each function it appears in
work.l:4:4: error: ‘num_lines’ undeclared (first use in this function)
\n {++num_lines; ++num_chars;}
^~~~~~~~~
work.l:4:17: error: ‘num_chars’ undeclared (first use in this function); did you mean ‘num_lines’?
\n {++num_lines; ++num_chars;}
^~~~~~~~~
num_lines
work.l: In function ‘main’:
work.l:15:23: error: ‘cnt’ undeclared (first use in this function); did you mean ‘int’?
return 0;
^
int
work.l:15:28: error: ‘num_lines’ undeclared (first use in this function)
return 0;
^
work.l:15:38: error: ‘num_chars’ undeclared (first use in this function); did you mean ‘num_lines’?
return 0;
^
num_lines
我没有得到上述error
,如果我像这样修改work.l
文件。
int cnt = 0,num_lines=0,num_chars=0; // then work properly above command.
%%
[" "]+[a-zA-Z0-9]+ {++cnt;}
\n {++num_lines; ++num_chars;}
. {++num_chars;}
%%
int yywrap()
{
return 1;
}
int main()
{ yyin = freopen("in.txt", "r", stdin);
yylex();
printf("%d %d %d\n", cnt, num_lines,num_chars);
return 0;
}
也就是说,如果我这一行int cnt = 0,num_lines=0,num_chars=0;
之前使用1 tab
,它工作正常。
现在我有两个问题:
这是行前
int cnt = 0,num_lines=0,num_chars=0;
配套使用1 tab
?为什么?逻辑解释。是解决这个错误的另一种解决方案吗?
我不是很肯定的标签问题,但有一种解释是,如果你不把标签,并在首节像写:
int cnt = 0;
然后注意的是,在第一部分你也可以写“捷径”,如:
Digit [0-9]
这是一个定义是不是编写所有的时间[0-9]
表示数字是什么数字正则表达式。
所以不使用标签在第一列写int cnt = 0;
时就像定义关键字INT(这可能就是错误告诉你did you mean int’?
)。所以选项卡是区分上述两种情况的一种方式。
根据弯曲为了写C/C++,它需要在里面代码:
%{ ... c/c++ code... %}
所以你的例子:%{ int cnt = 0,num_lines=0,num_chars=0; %}
所以我的事情最好的办法是写你%{ %}
内的c代码。
非常感谢您的好解释。 –
您是否阅读过有关定义部分格式的文档? – molbdnilo
是啊@molbdnilo。但我找不到这样的人。 –