Windows下 flex + bison 小例子

 

1.下载flex和bison,网址是http://gnuwin32.sourceforge.net/packages/flex.htm

http://gnuwin32.sourceforge.net/packages/bison.htm,如果这两个链接不好使了就自己搜吧。

这两个链接里面下载那两个Setup文件就好了。然后把他们安装了。

主要需要 lib文件夹下的 libfl.aliby.a 这两个库。

 

2.从 http://sourceforge.net/projects/winflexbison/ 下载已经编译好的压缩文件 win_flex_bison-2.5.1.zip(不到700kb)

 

3.把2中的路径添加到环境变量

 

4.编写两个文件,实现简单的计算器功能。

fb1-5.l代码:

/* Companionsource code for "flex & bison", published by O'Reilly 
* Media, ISBN 978-0-596-15597-1 
* Copyright (c) 2009, Taughannock Networks.All rights reserved. 
* See the README file for license conditionsand contact info. 
* $Header: /home/johnl/flnb/code/RCS/fb1-5.l,v2.1 2009/11/08 02:53:18 johnl Exp $ 
*/ 

/* recognizetokens for the calculator and print them out */ 

%{ 

# 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); } 

%%

  

fb1-5.y代码:

/* Companionsource code for "flex & bison", published by O'Reilly 
* Media, ISBN 978-0-596-15597-1 
* Copyright (c) 2009, Taughannock Networks.All rights reserved. 
* See the README file for license conditionsand contact info. 
* $Header: /home/johnl/flnb/code/RCS/fb1-5.y,v2.1 2009/11/08 02:53:18 johnl Exp $ 
*/ 

/* simplestversion of calculator */ 

%{ 

# include <stdio.h> 

%} 

/* declare tokens*/ 
%token NUMBER 
%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); 
}

 

5.编译

cmd控制台运行以下命令

win_bison -d fb1-5.y

生成 fb1-5.tab.h 和fb1-5.tab.c 文件

win_flex --nounistdfb1-5.l win_flex --wincompat fb1-5.l

生成 lex.yy.c 文件。--nounistd 和 --wincompat 选项使生成的 lex.yy.c 不依赖<unistd.h> 可以用 VC 编译,否则就只能用 gcc 编译了。

 

 

6.vs2008 新建一个vc++ 的空项目,把5中生成的fb1-5.tab.h、fb1-5.tab.c、lex.yy.c三个文件添加到项目。

编译报错:

原因是需要libfl.a这个库,需在项目中添加:

 

 

 

 7.效果演示:

 

posted @ 2017-05-03 19:58  那一剑的風情  阅读(9117)  评论(0编辑  收藏  举报