Run the following command to install Bison and Flex:
sudo apt update
sudo apt install bison flex -ysudo dnf install bison flex -ysudo pacman -S bison flexbrew install bison flexFor Cygwin:
- Open Cygwin setup and search for "bison" and "flex" in the package selection.
- Install them and complete the setup.
For MSYS2:
pacman -S mingw-w64-x86_64-bison mingw-w64-x86_64-flexAfter installation, check the installed versions:
bison --version
flex --versionIf both commands return version numbers, the installation is successful.
To compile a Bison and Flex project:
bison -d parser.y
flex lexer.l
gcc lex.yy.c parser.tab.c -o my_parser
./my_parser%{
#include "parser.tab.h"
%}
%%
[0-9]+ { yylval.num = atoi(yytext); return NUMBER; }
[+\-*/()] { return yytext[0]; }
[ \t\n] { /* Ignore whitespace */ }
. { printf("Unknown character: %s\n", yytext); }
%%
int yywrap() {
return 1;
}%{
#include <stdio.h>
#include <stdlib.h>
void yyerror(const char *s);
int yylex();
%}
%union {
int num;
}
%token <num> NUMBER
%token PLUS MINUS MULTIPLY DIVIDE LPAREN RPAREN
%left PLUS MINUS
%left MULTIPLY DIVIDE
%right UMINUS
%type <num> expr
%%
expr:
expr PLUS expr { $$ = $1 + $3; printf("Result: %d\n", $$); }
| expr MINUS expr { $$ = $1 - $3; printf("Result: %d\n", $$); }
| expr MULTIPLY expr { $$ = $1 * $3; printf("Result: %d\n", $$); }
| expr DIVIDE expr {
if ($3 == 0) {
printf("Error: Division by zero\n");
$$ = 0;
} else {
$$ = $1 / $3;
printf("Result: %d\n", $$);
}
}
| LPAREN expr RPAREN { $$ = $2; }
| MINUS expr %prec UMINUS { $$ = -$2; }
| NUMBER { $$ = $1; }
;
%%
void yyerror(const char *s) {
fprintf(stderr, "Error: %s\n", s);
}
int main() {
printf("Enter an expression:\n");
return yyparse();
}Once compiled, run the program:
./my_parserExample input:
3 + 4 * 2Expected output:
Result: 11