我已经寻找了答案,但是没有得到快速的简单示例响应。
我想使用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()。
提前感谢。