C 在函数中‘;yylex’;:';变量’;未申报的
我正在使用词汇分析。为此,我使用了C 在函数中‘;yylex’;:';变量’;未申报的,c,bison,flex-lexer,lexical-analysis,C,Bison,Flex Lexer,Lexical Analysis,我正在使用词汇分析。为此,我使用了Flex,并发现以下问题 工作,我 然后,我使用下面的命令,它正常工作并创建lex.yy.c Rezwans iMac:laqb-2 rezwan$flex work.l 然后,我使用下面的命令 Rezwans iMac:laqb-2 rezwan$gcc lex.yy.c-o b 并获得以下错误: work.l: In function ‘yylex’: work.l:3:4: error: ‘cnt’ undeclared (first use in th
Flex
,并发现以下问题
工作,我
然后,我使用下面的命令,它正常工作并创建lex.yy.c
Rezwans iMac:laqb-2 rezwan$flex work.l
然后,我使用下面的命令 Rezwans iMac:laqb-2 rezwan$gcc lex.yy.c-o b 并获得以下
错误
:
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
如果我像这样修改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;
}
也就是说,如果我在这一行之前使用1选项卡int cnt=0,num_line=0,num_chars=0代码>,它工作正常
现在我有两个问题:
是否需要在此行之前使用1选项卡int cnt=0,num_line=0,num_chars=0代码>?为什么?逻辑地解释
是否有另一种解决此错误的方法
我不太确定tab的问题,但有一种解释是,如果您不放置tab并在第一节中写下类似的内容:
int cnt = 0;
然后请注意,在第一部分中,您还可以编写“快捷方式”,如:
这是一个正则表达式,用于定义数字,而不是一直写入表示数字的[0-9]
因此,当写入int cnt=0时第一列中不使用tab的code>类似于定义关键字int(这可能就是为什么错误告诉您您是指int'?
)。所以tab是区分上述两种情况的一种方法
根据flex为了编写c/c++代码,它需要在内部:%{…c/c++代码…%}
因此对于您的示例:
%{
int cnt = 0,num_lines=0,num_chars=0;
%}
因此,我认为最好的方法是在%{%}
中编写c代码。您是否阅读了有关定义部分格式的文档?Yeah@molbdnilo。但是我找不到这样的。非常感谢你的解释。
Digit [0-9]
%{
int cnt = 0,num_lines=0,num_chars=0;
%}