flex和bison学习-简易计算器

flex中的文件 flex1-1.l

%{
#include "z.tab.h"
int yylval;    
%}

%%
[0-9]+ { yylval = atoi(yytext); return NUMBER; }
"+" { return ADD; }
"-" { return MIN; }
"*" { return MUL; }
"/" { return DIV; }
[ \t]+ { }
\n { return EOL; }
. { printf("Error = %c\n", *yytext); }
%%

bison中的文件 bison1-1.y

%{
#include <stdio.h>
int main(int argc, char **argv);
int yylex();
void yyerror(const char *s);    
%}

%token NUMBER;
%token ADD;
%token MIN;
%token MUL;
%token DIV;
%token EOL;

%%
calculater: 
    | calculater exp EOL { $$ = $2; printf("计算结果= %8d\n", $$); }
    ;

exp: factor
    | exp ADD factor { $$ =  $1 + $3; }
    | exp MIN factor { $$ = $1 - $3; }
    ;

factor: term
    | factor MUL term { $$ = $1 * $3; }
    | factor DIV nozero { $$ = $1 / $3; }
    ;

term: NUMBER
    ;

nozero: NUMBER { $$ = $1 != 0 ? $1 : 1; }
    ;
%%

int main(int argc, char **argv)
{
    yyparse();
    return 0;
}

void yyerror(const char *s) 
{
    fprintf(stderr, "error = %s\n", s);
}

执行命令:

bison -d bison1-1.y /* 会生成 bison1-1.tab.h  bison1-1.tab.c */

flex flex1-1.l /* 会生成 lex.yy.c */

cc $@ bison1-1.tab.c lex.yy.c -ll -o cal /* $@目标文件 -o要输出的文件 即生成可执行文件 cal */

./cal

注意:

  • flex文件中不需要main函数。
  • flex文件中的yylval要声明,否则会报错
  • bison文件中,flex文件中设计的变量要用%token声明下
  • bison文件中,要对设计到的函数进行声明
  • flex文件是词法分析文件, bison文件中是语法分析文件
posted @ 2021-03-23 16:48  jisa  阅读(181)  评论(0编辑  收藏  举报