use*_*848 6 c++ parsing lexer flex-lexer
我正在写尝试学习 Flex / Bison。我现在已经有了一些基本的 C 示例,但我想继续制作 C++ AST 树。c++ 使这种类型的面向对象程序比 C 更容易。但是,Flex 的 c++ 生成似乎存在问题,我不确定如何解决它。我想添加一些用于警告/错误报告的方法,因此我将从 yyFlexLexer 继承,并在我的 '.l' 文件中调用诸如 warning(const char* str) 和 error(const char* str) 等适当的内容。
然而,当我尝试按照我相信文档所说的方式执行继承时,我收到“yyFlexLexer redefinition”错误等。
词法分析器l
%option nounistd
%option noyywrap
%option c++
%option yyclass="NLexer"
%{
#include "NLexer.h"
#include <iostream>
using namespace std;
%}
%%
[ \t]+
\n { return '\n';}
[0-9]+(\.[0-9]+)? { cout << "double: " << atof(YYText()) << endl;}
. {return YYText()[0];}
%%
int main(int , char**)
{
NLexer lexer;
while(lexer.yylex() != 0) { };
return 0;
}
Run Code Online (Sandbox Code Playgroud)
NLexer.h
#ifndef NLEXER_H
#define NLEXER_H
#include <FlexLexer.h>
class NLexer : public yyFlexLexer
{
public:
virtual int yylex();
};
#endif
Run Code Online (Sandbox Code Playgroud)
很多错误:
错误 1 错误 C2011: 'yyFlexLexer': 'class' 类型重新定义 c:\users\chase_l\documents\visual studio 2013\projects\nlanguage\nlanguage\include\flexlexer.h 112 1 NLanguage
错误 2 错误 C2504: 'yyFlexLexer': 基类未定义 c:\users\chase_l\documents\visual studio 2013\projects\nlanguage\nlanguage\nlexer.h 6 1 NLanguage
与 yyFlexLexer 内的标识符相关的大约 80 个不存在。
我可以发布生成的 cpp 文件,但它是一个 1500 行自动生成的混乱文件。
编辑:显然这是 yyFlexLexer 的 MacroDefinition 的问题,因此它可以生成不同的基类 xxFlexLexer 等。如果您的项目中只需要 1 个词法分析器(可能),您只需执行以下操作即可使其正常工作。如果有人有比这更好的方法,请告诉我。
#ifndef NLEXER_H
#define NLEXER_H
#undef yyFlexLexer
#include <FlexLexer.h>
class NLexer : public yyFlexLexer
{
public:
virtual int yylex();
};
#endif
Run Code Online (Sandbox Code Playgroud)
在生成的lexer.yy.cc
文件中,您可以找到有关您的问题的旧评论:
/* C++ 扫描器一团糟。FlexLexer.h 头文件依赖于 * 下面的宏。这是通过回归套件中的 c++-multiple-scanners * 测试所必需的。我们收到报告称它破坏了继承。 * 我们将在 Flex 的未来版本中解决这个问题,或者完全省略 C++ 扫描器 *。*/
#define yyFlexLexer yyFlexLexer
yyFlexLexerOnce
include Guard 可用于克服它。NLexer.h
:
#ifndef NLEXER_H
#define NLEXER_H
#if !defined(yyFlexLexerOnce)
#include <FlexLexer.h>
#endif
class NLexer : public yyFlexLexer
{
public:
virtual int yylex();
};
#endif
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1668 次 |
最近记录: |