I have tried the below lex and yacc file and it seems like there are multiple definitions for many functions like yylex, yyrestart, and many more. I tried several ways and the online materials but could not resolve it. Any help could be appreciated.
try1.l file is as below,
%{
#include "y.tab.h"
int linenum=1;
int temp_int;
%}
%%
\n {linenum++;}
[\t ] /* skip spaces */;
\/\/[^\n]* /* ignore comments */;
"+" {return '+';}
"-" {return '-';}
"*" {return '*';}
"/" {return '/';}
")" {return ')';}
"(" {return '(';}
[0-9]+ {sscanf(yytext, "%d", &temp_int);
yylval.int_val = temp_int;
return INT;}
. {printf("LEX: unknown input string found in line %d \n", linenum);
abort();}
%%
int yywrap(void) {return 1;}
try1.y file as below,
/* Put new code here */
%{
#include <stdio.h>
#include <ctype.h>
extern int linenum;
%}
/* define all types of variables and terminals */
%union{
int int_val;
}
/* define the individual types of variables and terminals */
%token <int_val> INT
%type <int_val> expr
/* assign priorities to operators in order to
avoid shift/reduce conflicts (grammar ambiguities) */
%left '+' '-'
%left '*' '/'
%left UMINUS
/* the start variable of your program */
%start program
/* The main Grammar with its actions */
%%
program : expr {printf("Expr value = %d \n", $1);}
| error {printf("YACC: syntax error near line %d \n", linenum);
abort();}
;
expr :'('expr')' {$$ = $2;}
| expr '+' expr {$$ = $1 + $3;}
| expr '-' expr {$$ = $1 - $3;}
| expr '*' expr {$$ = $1 * $3;}
| expr '/' expr {$$ = $1 / $3;}
| '-' expr %prec UMINUS {$$ = -$2;}
| INT {$$ = $1;}
;
%%
/* link lex code */
#include "lex.yy.c"
/* insert additional code here */
int main(){
return yyparse();
}
int yyerror(char *s) {fprintf(stderr, "%s \n",s);}
The output is as below,
You're seeing this problem because the source code for the lexical analyser is being included twice.
When using both lex & yacc (or flex and bison), the generated compiler (the yacc output) typically #include
s the generated lexical analyser source.
You can see this in your try1.y
and the output try1.tab.c
code:
/* link lex code */
#include "lex.yy.c"
/* insert additional code here */
So either remove that manually from the try1.tab.c
, or do not compile the lex.yy.c
along with the try1.tab.c
.
Probably just:
$ flex try1.l
$ bison -d try1.y
$ gcc -g -Wall try1.tab.c -o try1.exe
Will get you going.