我是靠谱客的博主 寂寞蜡烛,这篇文章主要介绍flex+bison一起使用的超简单例子,现在分享给大家,希望可以做个参考。

一个纯整数的计算器。

flex文件:

flex.l:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*definitions : alias re-string*/ %{ #include <stdlib.h> #include <stdio.h> #include "bison.tab.h" %} number [0-9]+ %% {number} {yylval = atoi(yytext);return NUM; } [-+//*()^n] {return *yytext;} [ t] ; %% /* 到达文件末尾的回调函数 */ int yywrap(void) { /* We reached the end of the input file... */ /* Should we continue with another file? */ /* If so: * open the new file... * return 0; */ /* to stop processing... * return 1; */ return 1; /* Stop scanning at end of input file. */ }

可以看到仅仅就使用了一个NUM。

bison文件:

bison.y:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
%{ #define YYSTYPE int #include <math.h> #include <stdio.h> int yylex (void); void yyerror (char const *); %} %token NUM %left '-' '+' %left '*' '/' %left NEG /* negation--unary minus */ /* 负号 */ %right '^' /* exponentiation */ /* 幂运算 */ %% /* The grammar follows. */ /* 下面是语法 */ input: /* empty */ | input line ; line: 'n' | exp 'n' { printf ("out:%dn", $1); } | error 'n' { yyerrok;} ; exp: NUM { $$ = $1; } | exp '+' exp { $$ = $1 + $3; } | exp '-' exp { $$ = $1 - $3; } | exp '*' exp { $$ = $1 * $3; } | exp '/' exp { $$ = $1 / $3; } | '-' exp %prec NEG { $$ = -$2; } | exp '^' exp { $$ = pow ($1, $3); } | '(' exp ')' { $$ = $2; } ; %% int main (void) { return yyparse (); } /* Called by yyparse on error. */ void yyerror (char const *s) { fprintf (stderr, "error:%sn", s); }

编译命令:

复制代码
1
bison -d bison.y && flex flex.l && gcc *.c -w -lm && ./a.out

 

这里虽然例子极为简单,要注意的细节还不少:

  • flex.l中的#include "bison.tab.h",该头文件是bison 进行生成的,才能达到两者统一的目的
  • yylval = atoi(yytext); 在flex.l这一行十分重要,因为他将缓存在yytext中的字符进行了转换,以整数传递出去。

  • 注意两者的内在联系,调用了yyparse(),bison是会去寻找yylex()的实现,而这里yylex函数是使用flex felx.l命令编译之后自动生成的

 

 

最后

以上就是寂寞蜡烛最近收集整理的关于flex+bison一起使用的超简单例子的全部内容,更多相关flex+bison一起使用内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(65)

评论列表共有 0 条评论

立即
投稿
返回
顶部