如何把flex和bison产生的源文件结合起来?
很简单的一个问题,无奈我接受能力太差,对bison和flex掌握不好,希望大家看看。
我的几个文件如下,想法就是把lex识别的单词装入一个列表中去,但是不行啊。
想让生成的代码是的C++的,引入的头文件都是c++ 的,但是编译文件的时候就出问题了,说tokens.push_front(temp);中赋值有问题,二者不可以互相转换。但是在独立的cpp文件这个是可以的。
////////////////////////////////////////
test.ypp
%{
#include "header.h"
#define YYSTYPE char*
extern FILE* yyin;
extern int yyparse();
extern void yyerror(const char*);
extern int yyFlexLexer::yylex();
list<string> tokens;
%}
%token NAME
%token NUMBER
%%
List : /* empty is OK*/
| List NAME
{
printf("get a name from lex:%s\n",$2);
string temp($2);//not ok here,strange.
tokens.push_front(temp);
/*
tokens.push_front($2);
*/
}
| List NUMBER
{
printf("get a number from lex:%s\n",$2);
string temp($2);
tokens.push_front(temp);
}
%%
int main(int args,char* argv[])
{
if(args<=1 || NULL==(yyin=fopen(argv[1],"rt")))
{
printf("input File not specified.");
return 1;
}
yyparse();
int i = 0;
for(list<string>::iterator p = tokens.begin();p!=tokens.end();p++)
{
printf("%d: %s\n",++i,(*p).c_str());
}
fclose(yyin);
return 1;
}
////////////////////////////////////////
test.l
%{
#include "header.h"
extern YYSTYPE yylval;
%}
char [a-zA-Z\_]
digit [0-9]
name (({char})|"_")({char}|{digit}|"_")+
number ({digit})+
%%
{name} {
yylval = yytext;
return NAME;
}
{number} {
yylval = yytext;
return NUMBER;
}
[\ \t\n]+ { }
. {}
%%
int yywrap()
{
return 1;
}
void yyerror(const char* a)
{
printf("%s\n",a);
}
/////////////////////////////////////////////////////
header.h
#ifndef HEADER_H
#define HEADER_H
#include <cstdio>
#include <cctype>
#include <list>
#include <string>
using namespace std;
#endif