1.下載flex和bison,網址是http://gnuwin32.sourceforge.net/packages/flex.htmc++
和http://gnuwin32.sourceforge.net/packages/bison.htm,若是這兩個連接很差使了就本身搜吧。flex
這兩個連接裏面下載那兩個Setup文件就行了。而後把他們安裝了。spa
主要須要 lib文件夾下的 libfl.a 和 liby.a 這兩個庫。.net
2.從 http://sourceforge.net/projects/winflexbison/ 下載已經編譯好的壓縮文件 win_flex_bison-2.5.1.zip(不到700kb)code
3.把2中的路徑添加到環境變量htm
4.編寫兩個文件,實現簡單的計算器功能。blog
fb1-5.l代碼:token
/* 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代碼:ip
/* 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.編譯get
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.效果演示: