flex与bison编译
1,flex编译生成头文件和源文件
[sbinhuang@fengyi test]$ flex --header-file=flex_calculator.hpp -o flex_calculator.cpp --c++ calculator_example.l
其中,
-
–header-file 指定生成头文件名
-
-o 指定生成源文件名
-
–c++ 指定生成c++代码,c代码则无需指定;
-
最后指定flex源文件
-
注意:
--c++ 选项存在bug,生成的flex源文件中,有些函数、变量未定义,例如:yylineno
2,bison编译生成头文件和源文件
[sbinhuang@fengyi test]$ bison --defines=bison_calculator.hpp -o bison_calculator.cpp calculator_example.ypp
其中,
- –defines 指定生成头文件名
- -o 指定输出源文件名
- 最后指定bison源文件名,后缀为y,则生成c代码;后缀为ypp,则生成cpp代码
3,简单加减乘计算器例程
-
flex文件:calculator_example.l,将生成flex_calculator.cpp,flex_calculator.hpp
%option noyywrap nodefault yylineno %{ #include "common.hpp" #include "bison_calculator.hpp" %} EXP ([Ee][+-]?[0-9]+) %% "+" | "-" | "*" | "/" | "|" | "(" | ")" { return yytext[0]; } [0-9]+"."[0-9]*{ EXP}? | "."?[0-9]+{ EXP}? { yylval.d = atof(yytext); return NUMBER; } \n { return EOL; } "//".* [ \t] { } . { yyerror("Mystery character %c\n", *yytext); } %%
-
bison文件:calculator_example.ypp,将生成bison_calculator.cpp,bison_calculator.hpp
%{ #include <cstdio> #include <cstdlib> #include "common.hpp" #include "bison_calculator.hpp" %}