【Flex&Bison】简单样例

flex

test.l

%{
#include 
#include 
#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 

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

运行

【Flex&Bison】简单样例_第1张图片

你可能感兴趣的:(c++,c语言)