- 论坛徽章:
- 2
|
10可用积分
本帖最后由 cdsfiui 于 2016-09-22 18:15 编辑
我在网上找到了一个计算器的实现:
首先,有my.l文件如下:
- %{
- #include <stdio.h>
- #include <stdlib.h>
- #include "my.tab.h"
- extern int yylval;
- %}
- number [0-9]+
- %%
- {number} {yylval=atoi(yytext);printf("%s",yytext);return NUMBER;}
- "+" {printf("%s",yytext);return PLUS;}
- "-" {printf("%s",yytext);return SUB;}
- "*" {printf("%s",yytext);return CHEN;}
- "/" {printf("%s",yytext);return DIV;}
- "(" {printf("%s",yytext);return LKUO;}
- ")" {printf("%s",yytext);return YKUO;}
- %%
复制代码
然后有my.y文件
- %{
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- #define YYSTYPE int
- %}
- %token NUMBER
- %token PLUS
- %token SUB
- %token CHEN
- %token DIV
- %token LKUO
- %token YKUO
- %left PLUS SUB
- %left CHEN DIV
- %%
- com: exp {printf("=%d/n",$1);};
- exp: exp PLUS fac {$=$1+$3;}
- |exp SUB fac {$=$1-$3;}
- |fac{$=$1;};
- fac:fac CHEN term {$=$1*$3;}
- |fac DIV term {$=$1/$3;}
- |term {$=$1;};
- term:LKUO exp YKUO {$=$1;}
- | NUMBER {$=$1;};
- %%
- extern int yylex();
- int yyparse();
- main()
- {
- return yyparse();
- }
- yyerror()
- {printf("sytax error");}
复制代码
然后联合编译
- $ yacc my.y
- $ lex my.l
- $ gcc lex.yy.c my.tab.c -ll
- my.tab.c: In function ‘yyparse’:
- my.tab.c:1124:16: warning: implicit declaration of function ‘yylex’ [-Wimplicit-function-declaration]
- yychar = yylex ();
- ^
- my.tab.c:1307:7: warning: implicit declaration of function ‘yyerror’ [-Wimplicit-function-declaration]
- yyerror (YY_("syntax error"));
- ^
- my.y: At top level:
- my.y:30:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
- main()
- ^
- my.y:34:1: warning: return type defaults to ‘int’ [-Wimplicit-int]
- yyerror()
- ^
复制代码
yylex是lex的标准函数,为什么gcc说找不到这个定义?
|
|