在UNIX系统下联合编译flex 和bison 程序

flex 是一款词法解析开程序,而bison是一款语法解析开源程序。他们配合使用,就可以完成某些计算机脚本语言的语言的解析,如sql。这次我主要介绍flex 和bison在unix系统下的编译。

先看flex 代码:

%{
    #include "fb1-5.tab.h"//该文件由bison后面的bison生成。主要定义了token 的值。和yylval变量
%}

%%
"+"    { return ADD; }//匹配上“+”,就返回token ADD,yylval 此时的值为259
"-"    { return SUB; }
"*"    { return MUL; }
"/"    { return DIV; }
"|"     { return ABS; }
"("     { return OP; }
")"     { return CP; }
[0-9]+    { yylval = atoi(yytext); return NUMBER; }

\n      { return EOL; }
"//".*  
[ \t]   { /* ignore white space */ }
.    { yyerror("Mystery character %c\n", *yytext); }
%%

bison代码:

%{
#  include <stdio.h>
%}

/* declare tokens */
%token NUMBER //声明token
%token ADD SUB MUL DIV ABS
%token OP CP
%token EOL

%%

calclist: /* nothing */
 | calclist exp EOL { printf("= %d\n> ", $2); }
 | calclist EOL { printf("> "); } /* blank line or a comment */
 ;

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

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

term: NUMBER
 | ABS term { $$ = $2 >= 0? $2 : - $2; }
 | OP exp CP { $$ = $2; }
 ;
%%
main()
{
  printf("> "); 
  yyparse();
}

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

 

在终端运行命令:

cd /flex 和bison文件所在目录

bison -d fb.y (fb 为bison文件,命令成功执行后,会生成fb.tab.h 和fb.tab.c两个文件)

flex fb.l (fb.l为flex文件,会生成flex.yy.c文件。但是上述代码在我的系统里面抱错了,因为我的系统里面没有fl库,所以没有yywrap()函数

解决方案如下:在原来的fb.l文件中,最后一行,添加一个yywrap()函数。详见代码)

%{
    #include "fb1-5.tab.h"
%}

%%
"+"    { return ADD; }
"-"    { return SUB; }
"*"    { return MUL; }
"/"    { return DIV; }
"|"     { return ABS; }
"("     { return OP; }
")"     { return CP; }
[0-9]+    { yylval = atoi(yytext); return NUMBER; }

\n      { return EOL; }
"//".*  
[ \t]   { /* ignore white space */ }
.    { yyerror("Mystery character %c\n", *yytext); }
%%
yywrap() { return 1; }

cc fb.tab.c lex.yy.c (运行成功的话,会在当前目录生成a.out 可执行文件)

./a.out (运行该可执行文件)

 

转载于:https://www.cnblogs.com/tang-yi/p/5385171.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值