Flex&Bison就是Yacc&Lex的升级版。
本篇不是新手教程,新手教程可以看
https://www.cnblogs.com/longyi1234/archive/2010/03/19/1689769.html
还有这个作者的四篇文章
https://www.jianshu.com/p/3e58f0aceaa3
安装
sudo apt-get install flex bison
下面直接上代码
lexya_a.l
%{
#include "stdio.h"
#define YYSTYPE char*
/* 这个#define必须放在下面那个头文件上面,改变YYSTYPE类型,YYSTYPE类型将会定义下面的yylval */
/* 我们可以把char*改为自定义的union类型 */
/* .y文件也要写这个#define */
#include "lexya_a.tab.h"
extern "C" int yylex();/* 不写这个不能用g++编译,即不能使用cpp的库,不过可以用gcc编译 */
%}
%%
[a-z][a-z0-9]* {yylval = strdup(yytext);return STR; }
[ \t] ; /* ignore white space */
. ;
%%
lexya_a.y
%{
#include <stdio.h>
extern "C" int yylex();
void yyerror(char *);
#define YYSTYPE char*
/* 这个#define 决定了下面的$n,可以是$1、$2.....*/
%}
%token STR
%%
calculation: STR{printf("%s",$1);}
;
%%
void yyerror(char *s) {
printf("%s\n", s);
}
int main(void) {
yyparse();
return 0;
}
编译命令
flex *.l
bison -d *.y
g++ -o cal *.c -lfl
运行结果,我输入了asdas,输出了一样的结果,传递字符串成功。
./cal
asdas
asdas
使用union的版本,就是在.y文件下声明,在第一个%}和%%之间写下
%union {
int iValue; /* integer value */
char *sIndex; /* symbol table index */
};
%token <iValue> INTEGER
%token <sIndex> VARIABLE
接着,在.l的文件下,%%和%%之间写
[1-9][0-9]* {
yylval.iValue = atoi(yytext);
return INTEGER;
}
[a-z][a-z0-9]* {
yylval.sIndex= strdup(yytext);
return VARIABLE;
}
就能传递字符串了。