简单的Flex / Bison C ++

时间:2009-10-20 17:48:25

标签: c++ yacc bison lex

我已经找到了答案,但我没有得到任何快速回复的简单例子。

我想使用g ++编译flex / bison扫描器+解析器,因为我想使用C ++类来创建AST和类似的东西。

通过互联网搜索我发现了一些漏洞,所有人都说只需要在lex文件中使用extern“C”来声明一些函数原型。

所以我的shady.y文件是

%{
#include <stdio.h>
#include "opcodes.h"
#include "utils.h"

void yyerror(const char *s)
{
    fprintf(stderr, "error: %s\n", s);
}

int counter = 0;

extern "C"
{
        int yyparse(void);
        int yylex(void);  
        int yywrap()
        {
                return 1;
        }

}

%}

%token INTEGER FLOAT
%token T_SEMICOL T_COMMA T_LPAR T_RPAR T_GRID T_LSPAR T_RSPAR
%token EOL

%token T_MOV T_NOP


%% 

... GRAMMAR OMITTED ...

%%

main(int argc, char **argv)
{
    yyparse();
}

而shady.l文件是

%{
    #include "shady.tab.h"
%}

%%

"MOV"|"mov" { return T_MOV; }
"NOP"|"nop" { return T_NOP; }

";" { return T_SEMICOL; }
"," { return T_COMMA; }
"(" { return T_LPAR; }
")" { return T_RPAR; }
"#" { return T_GRID; }
"[" { return T_LSPAR; }
"]" { return T_RSPAR; }
[1-9][0-9]? { yylval = atoi(yytext); return INTEGER;}
[0-9]+"."[0-9]+ | "."?[0-9]? { yylval.d = atof(yytext); return FLOAT; }
\n { return EOL; }
[ \t] { /* ignore whitespace */ }
. { printf("Mystery character %c\n", *yytext); }

%%

最后在makefile中我使用g ++而不是gcc:

shady: shady.l shady.y
bison -d shady.y -o shady.tab.c
flex shady.l
g++ -o $@ shady.tab.c lex.yy.c -lfl

flex和bison正常工作但在链接时我收到以下错误:

Undefined symbols:
  "_yylex", referenced from:
  _yyparse in ccwb57x0.o

当然,如果我尝试在bison文件中更改任何有关该函数的内容,则表示yylex未在yyparse范围内声明。

我是否试图解决比看起来更复杂的事情?实际上我不需要一个封闭的结构来以面向对象的方式访问解析和词法分析器,我只是想让它工作。

我只是希望能够在bison文件中使用C ++(创建AST)并从C ++对象调用yyparse()。

提前致谢

1 个答案:

答案 0 :(得分:10)

extern "C" {} yylex shady.l需要%{ extern "C" { int yylex(void); } #include "shady.tab.h" %} %% "MOV"|"mov" { return T_MOV; } "NOP"|"nop" { return T_NOP; } ...etc...

  559  flex shady.l
  560  bison -d shady.y
  561  g++ shady.tab.c lex.yy.c 

此外,在添加虚拟语法规则后,我能够使用以下内容构建并运行它:

{{1}}
相关问题