Ubuntu下运行lex和yacc实现的简单计算器

安装Ubuntu和环境

Ubuntu装好后, 需要安装build-essential,gcc,flex,bison

sudo apt-get install build-essential gcc flex bison

lex文件

%{
#include "test.tab.h"
extern int yylval;
%}

%%
[0-9]+  { yylval = atoi(yytext); return NUMBER; }
[ \t]   ;       /* ignore white space */
\n  return 0;   /* logical EOF */
.   return yytext[0];
%%

Yacc文件

%token NAME NUMBER
%%
statement:  NAME '=' expression
    |   expression      { printf("= %d\n", $1); }
    ;

expression: expression '+' NUMBER   { $$ = $1 + $3; }
	|	expression '-' NUMBER	{ $$ = $1 - $3; }
	|	NUMBER			{ $$ = $1; }
    ;
%%
int main()
{
    yyparse();
    return 0;
}

int yyerror(char *s)
{
    printf("%s/n",s);
    return 0;
}

运行方式

1)首先,编译lex文件,生成lex.yy.c文件

flex test.l

2)其次,编译yacc文件,生成test.tab.h 与test.tab.c文件

bison -d test.y

3)链接生成的.c 文件,并生成相应的可执行文件

gcc -o test test.tab.c lex.yy.c -ly -lfl

4)运行可执行文件,计算简单表达式

./test

Untitled

报错信息及处理

可以参考https://blog.csdn.net/cctt_1/article/details/5393914

博文参考自https://blog.csdn.net/fly_yr/article/details/43014957

猜你喜欢

转载自blog.csdn.net/qq_31805821/article/details/80732170