编译lex和yacc文件的大量错误

问题描述 投票:0回答:1

我正在尝试使用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;
}

提前致谢。

c flex-lexer yacc
1个回答
2
投票

void yyerror(char *).y文件中.l后你丢失了一个分号。因此编译器需要在生成的代码中跟在它后面的行上的;,从而导致您看到的错误消息。

© www.soinside.com 2019 - 2024. All rights reserved.