0
votes

I have been following a calculator example from the book Flex and Bison from O'Reilly and so far I have done the following.

I am using Flex and Bison for Windows, and for compiling it with Flex I have made it with the following command:

flex f4.l

and for getting the needed .exe file I have put:

gcc lex.yy.c -L "C:\Program\GnuWin32\lib" -lfl

Until this point the generated .exe file works just fine.

Now the book says that I should make the .y file to be compiled by bison, my code is:

File: f5.y

    /* simplest version of calculator */
%{
#include <stdio.h>
%}
/* declare tokens */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%%
calclist: /* nothing */ 
 | calclist exp EOL { printf("= %d\n", $1); } 
 ;
exp: factor 
 | exp ADD factor { $$ = $1 + $3; }
 | exp SUB factor { $$ = $1 - $3; }
 ;
factor: term 
 | factor MUL term { $$ = $1 * $3; }
 | factor DIV term { $$ = $1 / $3; }
 ;
term: NUMBER 
 | ABS term { $$ = $2 >= 0? $2 : - $2; }
;
%%
main(int argc, char **argv)
{
 yyparse();
}
yyerror(char *s)
{
 fprintf(stderr, "error: %s\n", s);
}

Two files are generated by Bison: f5.tab.c and f5.tab.h

My f4.l file is the following:

%{
# include "f5.tab.h"
int yylval;
%}
/* recognize tokens for the calculator and print them out */
%{
 int yylval;
%}

%%
"+" { return ADD; }
"-" { return SUB; }
"*" { return MUL; }
"/" { return DIV; }
"|" { return ABS; }
[0-9]+ { yylval = atoi(yytext); return NUMBER; }
\n { return EOL; }
[ \t] { /* ignore whitespace */ }
. { printf("Mystery character %c\n", *yytext); }
%%
/*main(int argc, char **argv)
{
 int tok;
 while(tok = yylex()) {
 printf("%d", tok);
 if(tok == NUMBER) printf(" = %d\n", yylval);
 else printf("\n");
 }
}*/

I compile my program with:

gcc f5.tab.c lex.yy.c -L "C:\Program\GnuWin32\lib" -lfl

The problem is when I run the compiled program, for example if I put:

2 + 3 * 4
= 1968511970
20/2
= 1968511970

why have I those answers? It seems that is displaying memory positions, I guess, any help?

1
thank you @BrianTompsett-汤莱恩, I have edited the file, used flex again, but I still got the same errorLittle
The error message says that gcc couldn't find the library -lfl. Check that you are specifying the correct path. (Apparently it did find the library when you compiled the flex executable. So verify that the compiler flags were the same.)rici
The only thing you need -lfl for is yywrap, and you can avoid that requirement by adding %option noyywrap to your flex file, before the first %%.rici

1 Answers

2
votes
| calclist exp EOL { printf("= %d\n", $1); } 

You're printing the wrong thing. It should be:

| calclist exp EOL { printf("= %d\n", $2); }