简单的Flex/Bison C++

15

我已经寻找了答案,但是没有得到快速的简单示例响应。

我想使用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

灵活和Bison工作正常,但链接时我得到以下错误:
Undefined symbols:
  "_yylex", referenced from:
  _yyparse in ccwb57x0.o

当我尝试更改bison文件中函数的任何内容时,它会提示yylex未在yyparse的作用域内声明。
我是不是正在尝试解决比看起来更复杂的问题?实际上,我并不需要一个封闭的结构来以面向对象的方式访问解析器和词法分析器,我只想让它正常工作。
我只想能够在bison文件中使用C++(创建AST),并从C++对象中调用yyparse()。
提前感谢。

Flex和Bison都有生成C++而不是C的标志。 - vonbrand
1
呃,使用不纯的、非可重入的 C 解析器和带有静态全局变量的 C++ 不是一个好主意。在 C++ 中,使用 flex 和 bison 更加清晰明了。https://www.gnu.org/software/bison/manual/bison.html#A-Complete-C_002b_002b-Example - user246672
1个回答

12
你需要在 shady.l 中使用 extern "C" {} 来包围 yylex 函数。
%{
    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 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接