ElF*_*Fik 7 lex flex++ flex-lexer
我们刚刚开始使用flex为项目构建词法分析器,但是我们无法弄清楚如何让它工作.我复制教程中给出的示例代码,并尝试以tut文件作为参数运行flex ++,但每次只收到一个错误.例如
输入文件(calc.l)
%name Scanner
%define IOSTREAM
DIGIT [0-9]
DIGIT1 [1-9]
%%
"+" { cout << "operator <" << yytext[0] << ">" << endl; }
"-" { cout << "operator <" << yytext[0] << ">" << endl; }
"=" { cout << "operator <" << yytext[0] << ">" << endl; }
{DIGIT1}{DIGIT}* { cout << " number <" << yytext << ">" << endl; }
. { cout << " UNKNOWN <" << yytext[0] << ">" << endl; }
%%
int main(int argc, char ** argv)
{
Scanner scanner;
scanner.yylex();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
用这个代码我得到
flex ++ calc.l
calc.l:1:bad character:%calc.l:1:unknown error processing section
calc.l:1:unknown error processing section
calc.l:1:unknown error processing section
calc.l :2:无法识别的'%'指令
谁能帮助我理解我在这里做错了什么?干杯
你可以尝试这样的事情:
%{ ... %}
到文件的前几行#include <iostream>
and using namespace std;
(而不是尝试定义 Scanner)%option noyywrap
上方添加yylex()
(而不是尝试调用不存在的扫描仪的方法)以您的示例为例,它可能看起来像这样:
%{
#include <iostream>
using namespace std;
%}
DIGIT [0-9]
DIGIT1 [1-9]
/* read only one input file */
%option noyywrap
%%
"+" { cout << "operator <" << yytext[0] << ">" << endl; }
"-" { cout << "operator <" << yytext[0] << ">" << endl; }
"=" { cout << "operator <" << yytext[0] << ">" << endl; }
{DIGIT1}{DIGIT}* { cout << " number <" << yytext << ">" << endl; }
. { cout << " UNKNOWN <" << yytext[0] << ">" << endl; }
%%
int main(int argc, char** argv)
{
yylex();
return 0;
}
Run Code Online (Sandbox Code Playgroud)