we are just getting started using flex to build a lexer for a project, but we cant figure out how to get it to work. I copy the example code given in tutorials and try to run flex++ with the tut file as its argument however I just receive an error each time. e.g.
input file (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;
}
with this code i get
flex++ calc.l
calc.l:1: bad character: % calc.l:1: unknown error processing section 1
calc.l:1: unknown error processing section 1
calc.l:1: unknown error processing section 1
calc.l:2: unrecognised '%' directive
could anyone help me understand what im doing wrong here? cheers
You might try something like:
%{ ... %}
to the first couple of lines in your file#include <iostream>
and using namespace std;
(instead of trying to define Scanner)
%option noyywrap
above the rules sectionyylex()
(instead of trying to call the method of a non-existant Scanner)
With your example, it could look something like this:
%{
#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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With