Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flex++ bad character error and more. new to flex

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

like image 493
ElFik Avatar asked Nov 06 '11 00:11

ElFik


1 Answers

You might try something like:

  • adding %{ ... %} to the first couple of lines in your file
  • adding #include <iostream> and using namespace std; (instead of trying to define Scanner)
  • adding %option noyywrap above the rules section
  • using just yylex() (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;
}
like image 175
summea Avatar answered Oct 08 '22 08:10

summea