gpt4 book ai didi

c - 编译 lex 和 yacc 文件时出现大量错误

转载 作者:太空宇宙 更新时间:2023-11-04 07:48:00 24 4
gpt4 key购买 nike

我正在尝试用 yacc/lex 制作一个简单的计算器,但我不断收到大量错误,其中很多人说错误在生成的文件中。

我运行 gcc lex.yy.c y.tab.c -o minicalc 并得到如下错误

bas.y:34:16: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token
int main(void) {
y.tab.c:499:2: error: expected declaration specifiers before ‘;’ token
};

这些是最常见的,但还有更多。问题是,我遇到了这样的错误

In file included from lex.yy.c:459:0:
/usr/include/unistd.h: In function ‘yyerror’:
/usr/include/unistd.h:258:22: error: storage class specified for parameter ‘useconds_t’
typedef __useconds_t useconds_t;
^~~~~~~~~~

这看起来好像错误不在我的代码中。

这是我的 lex 代码:

%{
#include <stdlib.h>
#include "y.tab.h"
void yyerror(char *)
%}

%%

/* a is value of last expresion */
a {
yyval = *yytext - 'a';
return LAST;
}

/* integers */
[0-9]+ {
yyval = atoi(yytext);
return INTEGER;
}

/* operators */
[-+()=/*\n] { return *yytext; }

/* skip whitespace */
[ \t] { ; }

/* all else is error */
. yyerror("invalid character");

%%

int yywrap(void) {
return 1;
}

这是我的 yacc 代码:

%token INTEGER LAST
%left '+' '-'
%left '*' '/'

%{
void yyerror(char *)
int yylex(void);
int lastval;
%}

%%

program:
program expr '\n' { lastval = $2; }
|
;

expr:
INTEGER
| LAST { $$ = lastval; }
| expr '+' expr { $$ = $1 + $3; }
| expr '-' expr { $$ = $1 - $3; }
| expr '*' expr { $$ = $1 * $3; }
| expr '/' expr { $$ = $1 / $3; }
| '(' expr ')' { $$ = $2; }
;

%%

void yyerror(char *) {
fprintf(stderr, "%s\n", s);
}

int main(void) {
yyparse();
return 0;
}

提前致谢。

最佳答案

.y.l 文件中的 void yyerror(char *) 后都缺少分号。因此,编译器期望在生成的代码中其后的行中有一个 ;,从而导致您看到的错误消息。

关于c - 编译 lex 和 yacc 文件时出现大量错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55698416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com