flex
test.l
%{
#include <stdio.h>
#include <string.h>
#include "test.tab.h"
void showError();
%}
numbers ([0-9])+
%%
{numbers} {yylval.number = atoi(yytext); return (NUM);}
";" {return (SEMICOLON);}
. {showError(); return(OTHER);}
[ \t\n]+
%%
void showError(){
printf("Other input\n");
}
int yywrap(){
return 1;
}
bison
test.y
%{
#include <stdio.h>
int yylex();
int yyerror(char *s);
%}
%token NUM OTHER SEMICOLON
%type <number> NUM
%union{
int number;
}
%%
prog:
stmts
;
stmts:
| stmt SEMICOLON stmts
stmt:
NUM {
printf("The number you entered is - %d\n", $1);
}
| OTHER
;
%%
int yyerror(char *s)
{
printf("Syntax Error on line %s\n", s);
return 0;
}
main 函数
main.c
#include "test.tab.h"
int main(int argc, char* argv[]) {
yyparse();
return 0;
}
MakeFile
all:
flex -l test.l
bison -dv test.y
gcc -o test test.tab.c lex.yy.c main.c -lfl