如何把flex和bison产生的源文件结合起来?

sailfar 2006-03-29 05:31:34
很简单的一个问题,无奈我接受能力太差,对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
...全文
236 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
healer_kx 2006-03-31
  • 打赏
  • 举报
回复
你干吗不试一试Antlr
sailfar 2006-03-30
  • 打赏
  • 举报
回复
大虾们看看啊

3,882

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 其它技术问题
社区管理员
  • 其它技术问题社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧