配置過程
- 下載
https://sourceforge.net/projects/winflexbison/?source=typ_redirect -
解壓縮
D:\WorkSpace\3_FlexBison\win_flex_bison-latest
解壓縮出來的文件 -
新建MFC工程
把FirstTry.cpp移除,因為后面的定義的Parser.y文件里面定義了一個main,這個main會生成到Parser.tab.cpp中鼻由。
image.png -
生成依賴項
生成依賴項
按圖示點擊其上的查找現(xiàn)有的按鈕尿赚,然后找到你下載的WinFlexBison工具的解壓目錄中的custom_build_rules目錄下的win_flex_bison_custom_build.targets。
- 設(shè)置可執(zhí)行目錄
D:\WorkSpace\3_FlexBison\win_flex_bison-latest
可執(zhí)行目錄 - 新建Parser.y
%{
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#define YYSTYPE double
void yyerror(const char *text);
int yylex(void);
%}
/////////////////////////////////////////////////////////////////////////////
// declarations section
// place any declarations here
%token NUMBER
%left '+' '-'
%left '*' '/'
%right '^'
%%
/////////////////////////////////////////////////////////////////////////////
// rules section
// place your YACC rules here (there must be at least one)
command : exp {printf("%lf\n",$1);}
;
exp : NUMBER {$$ = $1;}
| exp '+' exp {$$ = $1 + $3;}
| exp '-' exp {$$ = $1 - $3;}
| exp '*' exp {$$ = $1 * $3;}
| exp '/' exp {
if(0 != $3)
{
$$ = $1 / $3;
}
else
{
$$=0;
}
}
| exp '^' exp {$$ = pow($1,$3);}
| '(' exp ')' {$$ = $2;}
;
%%
/////////////////////////////////////////////////////////////////////////////
// programs section
int yylex(void)
{
// place your token retrieving code here
int c = 0;
while( (c = getchar()) == ' ');
if( isdigit(c) )
{
ungetc(c,stdin);
scanf_s("%lf",&yylval);
return (NUMBER);
}
if( '\n' == c )
{
return 0;
}
return c;
}
int main(void)
{
yyparse();
system("PAUSE");
return 0;
}
void yyerror(const char *text)
{
fprintf(stderr,"%s\n",text);
}
-
編譯
生成Parser.tab.h和Parser.tab.c庵佣,把這兩個文件加入到工程里面。注意要設(shè)置Parser.tab.c不使用預(yù)編譯頭。
不使用預(yù)編譯頭 -
再次編譯運行
運行 -
編譯效果
Yacc編譯Parser.y -> 生成Parser.tab.h和Parser.tab.cpp挖诸。
C/C++編譯鏈接Parser.tab.h和Parser.tab.cpp -> FirstTry.exe。
image.png