flex与bison编译

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"
    
    %}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值