未定义对yylval和yyerror的引用

时间:2019-02-07 20:52:53

标签: c gcc makefile bison flex-lexer

我正在尝试从书flex and Bison中汇编一个示例。我很想知道为什么会出现以下构建错误,以及如何纠正该错误?谢谢。

$ make
bison -d fb1-5.y
fb1-5.y: warning: 3 shift/reduce conflicts [-Wconflicts-sr]
flex fb1-5.l
cc -o  fb1-5.tab.c lex.yy.c -lfl
fb1-5.l: In function ‘yylex’:
fb1-5.l:27:3: warning: implicit declaration of function ‘yyerror’; did you mean ‘perror’? [-Wimplicit-function-declaration]
 . { yyerror("Mystery character %c\n", *yytext); }
   ^~~~~~~
   perror
/tmp/cctl5WLj.o: In function `yylex':
lex.yy.c:(.text+0x32f): undefined reference to `yylval'
lex.yy.c:(.text+0x363): undefined reference to `yyerror'
collect2: error: ld returned 1 exit status
Makefile:2: recipe for target 'fb1-5' failed
make: *** [fb1-5] Error 1

Makefile:

fb1-5:  fb1-5.l fb1-5.y
    bison -d fb1-5.y
    flex fb1-5.l
    cc -o  fb1-5.tab.c lex.yy.c -lfl

fb1-5.y

/* simplest version of calculator */

%{
#  include <stdio.h>
%}

/* declare tokens */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token OP CP
%token EOL

%%

calclist: /* nothing */
 | calclist exp EOL { printf("= %d\n> ", $2); }
 | calclist EOL { printf("> "); } /* blank line or a comment */
 ;

exp: factor
 | exp ADD exp { $$ = $1 + $3; }
 | exp SUB factor { $$ = $1 - $3; }
 | exp ABS factor { $$ = $1 | $3; }
 ;

factor: term
 | factor MUL term { $$ = $1 * $3; }
 | factor DIV term { $$ = $1 / $3; }
 ;

term: NUMBER
 | ABS term { $$ = $2 >= 0? $2 : - $2; }
 | OP exp CP { $$ = $2; }
 ;
%%
main()
{
  printf("> "); 
  yyparse();
}

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

fb1-5.l:

/* recognize tokens for the calculator and print them out */

%{
# include "fb1-5.tab.h"
%}

%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"|"     { return ABS; }
"("     { return OP; }
")"     { return CP; }
[0-9]+  { yylval = atoi(yytext); return NUMBER; }

\n      { return EOL; }
"//".*  
[ \t]   { /* ignore white space */ }
.   { yyerror("Mystery character %c\n", *yytext); }
%%

3 个答案:

答案 0 :(得分:3)

您必须将makefile更改为:

fb1-5:  fb1-5.l fb1-5.y
    bison -b fb1-5 -d fb1-5.y
    flex fb1-5.l
    gcc -o fb1-5 fb1-5.tab.c lex.yy.c -lfl -ly

产生正确的输出文件并具有yyerror的标准实现

答案 1 :(得分:2)

我想问题出在这里

cc -o   lex.yy.c  fb1-5.tab.c -lfl

答案 2 :(得分:2)

这里有两个独立的问题。

  1. yyerror未在扫描仪中声明(或在解析器中未声明)。 Bison不会为其生成声明,因此您需要在使用它的任何翻译部门中对其进行声明。

  2. cc -o fb1-5.tab.c lex.yy.c -lfl告诉C编译器编译lex.yy.c,将生成的可执行文件(编译器的输出)放入fb1-5.tab.c中。那不是你想要的。它会用可执行文件覆盖生成的解析器,并且不会编译生成的解析器,结果是解析器中定义的符号对链接器不可用。