0

I am studying compilers and studying Lex and Yacc. I write a LexYacc code as my teacher shows:

here is exp.l:

/*%option outfile="scanner.cpp"*/
%{
/*#include "exp.tab.h"*/
#include "y.tab.h"
extern int yylval;
%}
%%
0|[1-9][0-9]*           { yylval = atoi(yytext); return INTEGER; }
[+*()\n]                { return yytext[0]; }
.                       { /* do nothing */ }
%%

and this is exp.y:

/*
%output "parser.cpp"
%skeleton "lalr1.cc"
*/
%{ 
#include <stdio.h>
%} 

%token INTEGER

%left '+'
%left '*'

%% 
input   : /* empty string */
            | input line 
            ;
line    : '\n' 
            | exp '\n' { printf ("\t%d\n", $1); } 
            | error '\n'
            ;
exp : INTEGER { $$ = $1; }
            | exp '+' exp { $$ = $1 + $3; }
            | exp '*' exp { $$ = $1 * $3; } 
            | '(' exp ')' { $$ = $2; } ;
%%

main () {
  yyparse (); 
}


yyerror (char *s) {
  printf ("%s\n", s);
} 

and I use linux command to run it:

flex exp.l
bison -d exp.y
gcc exp.tab.c lex.yy.c -o exp -lfl

and it shows this:

exp.tab.c: In function ‘yyparse’:
exp.tab.c:1217:16: warning: implicit declaration of function ‘yylex’ [-Wimplicit-function-declaration]
 1217 |       yychar = yylex ();
      |                
exp.tab.c:1374:7: warning: implicit declaration of function ‘yyerror’; did you mean ‘yyerrok’? [-Wimplicit-function-declaration]
 1374 |       yyerror (YY_("syntax error"));
      |       
      |       yyerrok
exp.y: At top level:
exp.y:28:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
   28 | main () {
      | 
exp.y:33:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
   33 | yyerror (char *s) {
      |
exp.l:4:10: fatal error: y.tab.h: No such file or directory
    4 | #include "y.tab.h"
      |          
compilation terminated.

The whole program is mainly a calculator to calculate addition and multiplication. I don't know what happened and hope someone can help me.

dubugger
  • 89
  • 6
  • These implicit declarations are warnings. They are certainly worth taking care of but the real error that stops the compilation seems to be lack of the file imported in `#include "y.tab.h"`. – Piotr Siupa Nov 18 '21 at 07:58
  • yeah, I use `#include "exp.tab.h"` to replace it and it can compile. Thanks a lot. – dubugger Nov 18 '21 at 08:03
  • If you use a function they wasn't defined/declared before, the C language allows that and just assumes it exists. It's a bad practice to use this mechanism nowadays and hence, the compiler produces a warning. https://stackoverflow.com/q/9182763/3052438 You're probably missing some includes (maybe `exp.l.h` in `exp.y`) and declaration of functions that you define at the end of the file like `yyerror`. Also you don't have return types for some of the functions (`yyerror` again). I don't have the time to test anything rn so you have to experiment by yourself. – Piotr Siupa Nov 18 '21 at 08:11

0 Answers0