5

I know that in flex you just have to do yyin = fopen(filename, "r"); to read a file but if you want to do it from bison how is it possible? I'm trying to combine flex and bison for my purpose(read a file with 4 + 5 + 7; and print the outcome) but I have a hard time trying to open a file from bison. I tried to use extern FILE *yyin at the declaration room and after that yyin = fopen(filename, "r"); but I got the error:

C2065: 'yyin' : undeclared identifier.

This is my code just in case it helps to find it.

bison code:

%{
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
extern FILE *yyin;
int yyerror(char *message)
{
    return 0;
}
%}

%union {
 double val;
 char sym;
}   
%token <val> NUMBER
%token <sym> PLUS Q_MARK
%type <val> addition_list addition
%start addition_list
%%

addition_list : addition Q_MARK  {printf("apotelesma: %d\n", $1);}
| addition_list addition Q_MARK  {}
;

addition : NUMBER PLUS NUMBER {$$ = $1 + $3;}
| addition PLUS NUMBER {$$ = $1 + $3;}
;

%%
void main(int argc, char *argv[])
{
    yyin = fopen("argv[1]", "r");
    yyparse();
}

flex code:

%option noyywrap
%{
#include "flex2.tab.h"
%}

%%
\+ { flex2lval.sym = yytext[0];printf("%c\n", yytext[0]);  return PLUS; }
; { flex2lval.sym = yytext[0]; return Q_MARK; }
0|([-+]?(([1-9][0-9]*)|(0\.[0-9]+)|([1-9][0-9]*\.[0-9]+))) {flex2lval.val = atof(yytext); return NUMBER; }
%%
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
captain monk
  • 719
  • 4
  • 11
  • 34
  • I don't remember exactly because it's before 1 year.The code was ok, the problem was somewhere in the options of the compiler. – captain monk Jul 14 '15 at 16:08
  • Your `yyerror()` method should print that message (which will always say `"syntax error"` unless you're calling it yourself. Merely returning zero isn't helpful to the user. – user207421 Jul 05 '22 at 00:50

1 Answers1

0

Did you compile the file that flex produced along with the file bison produced?

flex lexical_file.l (produces lex.yy.c)

bison -d syntax_file.y (produces syntax_file.tab.c and syntax_file.tab.h)

gcc syntax_file.tab.c lex.yy.c -lfl -o myparser.out

Also you should remove the quotes around "argv[1]". It should be yyin = fopen(argv[1], "r"); if you want to successfully open the file that was passed as the first argument to the parser instead of trying to open a file that is actually named "argv[1]".

κροκς
  • 592
  • 5
  • 18