7

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

Lesmana
  • 25,663
  • 9
  • 82
  • 87
ElFik
  • 897
  • 2
  • 13
  • 31
  • Did you by chance get this from http://www.mario-konrad.ch/index.php?page=20024 ? I'm having the same problem although I've just this second downloaded it so I will look into it. – Ell Nov 10 '11 at 18:09
  • I'm getting the same error here. – JohnTortugo Jul 13 '12 at 20:51
  • I know this is a really old question... but I found at least one way to get this type of file to compile and run if you ever need it in the future. – summea Mar 14 '13 at 16:53

2 Answers2

3

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;
}
summea
  • 7,390
  • 4
  • 32
  • 48
0

What is the version of flex++ you using? I uses 'Function: fast lexical analyzer generator C/C++ V2.3.8-7 (flex++), based on 2.3.8 and modified by coetmeur@icdc.fr for c++' (-? option) and your cacl.c is processed perfectly..

For Win32, this version of Flex++/Bison++ is here

Egg Head
  • 369
  • 3
  • 4