"first use" 更改 lex 文件中的代码时出错
"first use" error when change the code in lex file
给定一个这样的 .l
文件:
%{
#include "y.tab.h"
%}
%%
[ \t\n]
"if" return IF_TOKEN ;
"while" return ELSE_TOKEN ;
. yyerror("Invalid Character");
%%
int yywrap(void){
return 1;
}
和这样的 .y
文件:
%{
#include <stdio.h>
void yyerror(char *);
%}
%token IF_TOKEN ELSE_TOKEN MINUS_TOKEN DIGIT_TOKEN
%%
program :expr {printf("program Accepted!!!");};
expr : IF_TOKEN | DIGIT_TOKEN ;
%%
void yyerror(char *s){
fprintf(stderr, "%s\n", s);
}
int main(){
yyparse();
return 0;
}
我使用这 3 个命令来编译这 2 个文件(我的 lex 文件名为 p.l 和我的 yacc 文件名为 p.y):
flex p.l
yacc -d p.y
gcc lex.yy.c y.tab.c
编译没有错误。但是当我将 "return ELSE_TOKEN" 更改为 "return WHILE_TOKEN" 时,出现此错误并且没有输出文件:
p.l: In function ‘yylex’:
p.l:10:8: error: ‘WHILE_TOKEN’ undeclared (first use in this function)
"while" return WHILE_TOKEN ;
^
p.l:10:8: note: each undeclared identifier is reported only once for each function it appears in
另外,当我将 "while" 更改为 "else" 并添加新规则时:
"for" return FOR_TOKEN ;
我得到同样的错误。我怎样才能更正代码以使其正常工作?
您没有添加:
%token WHILE_TOKEN FOR_TOKEN
语法,所以头文件没有包含 WHILE_TOKEN
或 FOR_TOKEN
的定义,所以词法分析器编译失败。
给定一个这样的 .l
文件:
%{
#include "y.tab.h"
%}
%%
[ \t\n]
"if" return IF_TOKEN ;
"while" return ELSE_TOKEN ;
. yyerror("Invalid Character");
%%
int yywrap(void){
return 1;
}
和这样的 .y
文件:
%{
#include <stdio.h>
void yyerror(char *);
%}
%token IF_TOKEN ELSE_TOKEN MINUS_TOKEN DIGIT_TOKEN
%%
program :expr {printf("program Accepted!!!");};
expr : IF_TOKEN | DIGIT_TOKEN ;
%%
void yyerror(char *s){
fprintf(stderr, "%s\n", s);
}
int main(){
yyparse();
return 0;
}
我使用这 3 个命令来编译这 2 个文件(我的 lex 文件名为 p.l 和我的 yacc 文件名为 p.y):
flex p.l
yacc -d p.y
gcc lex.yy.c y.tab.c
编译没有错误。但是当我将 "return ELSE_TOKEN" 更改为 "return WHILE_TOKEN" 时,出现此错误并且没有输出文件:
p.l: In function ‘yylex’:
p.l:10:8: error: ‘WHILE_TOKEN’ undeclared (first use in this function)
"while" return WHILE_TOKEN ;
^
p.l:10:8: note: each undeclared identifier is reported only once for each function it appears in
另外,当我将 "while" 更改为 "else" 并添加新规则时:
"for" return FOR_TOKEN ;
我得到同样的错误。我怎样才能更正代码以使其正常工作?
您没有添加:
%token WHILE_TOKEN FOR_TOKEN
语法,所以头文件没有包含 WHILE_TOKEN
或 FOR_TOKEN
的定义,所以词法分析器编译失败。