在函数’yylex’中:’变量’未声明

我正在使用Lexical Analysis 。 为此,我使用Flex ,我获取以下问题。

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 $ flex 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 

如果我像这样修改work.l文件,我没有上面的error

  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 tab int cnt = 0,num_lines=0,num_chars=0; ,它工作正常。

现在我有两个问题:

  1. 在此行之前必须使用1 tab int cnt = 0,num_lines=0,num_chars=0; ? 为什么? 逻辑解释。

  2. 是解决此错误的另一种解决方案吗?

我不太确定选项卡问题,但有一种解释是,如果你没有放置选项卡并在第一部分写入类似于:

 int cnt = 0; 

然后请注意,在第一部分中,您还可以编写“快捷方式”,例如:

 Digit [0-9] 

这是一个正则表达式,定义了什么数字,而不是一直写[0-9]来表示数字。

所以在写int cnt = 0; 在没有使用tab的第一列中就像定义关键字int(这可能是为什么错误告诉你did you mean int'? )。 因此tab是一种区分上述两种情况的方法。

根据flex来编写c / c ++代码,它需要在里面: %{ ... c/c++ code... %}所以对于你的例子:

 %{ int cnt = 0,num_lines=0,num_chars=0; %} 

所以我最好的方法是在%{ %}内编写你的c代码。