Windows下lex 與 yacc的使用
首先
下載下載flex和bison。網址是http://pan.baidu.com/s/1dDlfiW5
選擇下載就好了,下載後解壓到你電腦中的任一盤中。找到這個文件夾就行了。
然後裏面就是這樣:
打開flex
打開bison
至此萬事俱備,我們可以開始兩個簡單的文件來測試一下。
1.新建文本文件,更改名稱爲lex.l,敲入下面代碼
%{
int yywrap(void);
%}
%%
%%
int yywrap(void)
{
return 1;
}
2.新建文本文件,更改名稱爲yacc.y,敲入下面代碼
%{
void yyerror(const char *s);
%}
%%
program:
;
%%
void yyerror(const char *s)
{
}
int main()
{
yyparse();
return 0;
}
我們暫且不討論上面代碼的意思。
打開控制檯,進入到剛纔所建立文件(lex.l,yacc.y)所在的文件夾。
1.輸入 flex lex.l
2.輸入 bison yacc.y
如果我們看到當前文件夾上多了兩個文件(yacc.tab.c,lex.yy.c),那麼說明lex&&yacc已經安裝配置成功,接下來就好好享受這兩個小工具的魅力吧。
現在我們來試用下lex:
1、新建文本文件,更改名稱爲a.lex,敲入下面代碼-------詞法分析器的源代碼
%{
int wordCount = 0;
int numcount = 0;
%}
chars [A-Za-z\_\'\.\"]
numbers ([0-9])+
delim [" "\n\t]
whitespace {delim}+
words {chars}+
%%
while {ECHO; printf("%s\n",yytext);}
{words} { wordCount++;
/* increase the word count by one*/ }
{whitespace} { /* do nothing*/ }
([0-9])+ { numcount++; /* one may want to add some processing here*/ }
%%
void main()
{
printf("ok1\n");
yylex(); /* start the analysis*/
printf("ok2\n");
printf(" No of words: %d\n number: %d\n", wordCount, numcount);
return 0;
}
int yywrap()
{
return1;
}
3、打開菜單,運行,輸入cmd。
輸入:cd 文件夾路徑
輸入:flex a.lex 回車後生成一個 lex.yy.c文件
4.然後這個lex.yy.c文件打開並編譯一下就行了。
5.輸入測試代碼
asd asdf 23 q
a1
b2
!#@
while
運行看看就行了。
致謝
篤行者------lex&yacc安裝配置 http://blog.csdn.net/bedusing/article/details/5409495