MobiusT
MobiusT

Reputation: 95

How to overcome undeclared error in lex file

I am new to lex and I write very simple program in the file ilk.l


%option main
%%
float val;
[+-]?[0-9]*(\.)?[0-9]+      {sscanf(yytext, "%f", &val);
                             printf(">%f<", val);     }

After saving this file, I run the following commands;


-bash-4.2$ lex ilk.l
-bash-4.2$ gcc lex.yy.c
ilk.l: In function ‘yylex’:
ilk.l:3:1: error: ‘val’ undeclared (first use in this function)
 float val;
 ^
ilk.l:3:1: note: each undeclared identifier is reported only once for each function it appears in
-bash-4.2$

I am confused about the reason for error. Can you explain what I am doing wrong and how can I correct it?

Upvotes: 1

Views: 551

Answers (1)

Variables should be declared in declaration section as follows:

%{
//declaration section
float val;
%}
%option main
%%
[+-]?[0-9]*(\.)?[0-9]+ {sscanf(yytext, "%f", &val);printf(">%f<", val);}
%%

Upvotes: 1

Related Questions