Hello viewers, Today I am going to share an example of the lex program and compile using the flex tool installed previously. To know what is flex and how to install it in windows Click here.
Program code for .l file.
--first, create a "filename.l" file with the code given below-----and a "test.c" file ---
%{
int COMMENT=0;
%}
identifier [a-zA-Z][a-zA-Z0-9]*
%%
#.* {printf("\n%s is a preprocessor directive",yytext);}
int |
float |
char |
double |
while |
for |
struct |
typedef |
do |
if |
break |
continue |
void |
switch |
return |
else |
goto {printf("\n\t%s is a keyword",yytext);}
"/*" {COMMENT=1;}{printf("\n\t %s is a COMMENT",yytext);}
{identifier}\( {if(!COMMENT)printf("\nFUNCTION \n\t%s",yytext);}
\{ {if(!COMMENT)printf("\n BLOCK BEGINS");}
\} {if(!COMMENT)printf("BLOCK ENDS ");}
{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER",yytext);}
\".*\" {if(!COMMENT)printf("\n\t %s is a STRING",yytext);}
[0-9]+ {if(!COMMENT) printf("\n %s is a NUMBER ",yytext);}
\)(\:)? {if(!COMMENT)printf("\n\t");ECHO;printf("\n");}
\( ECHO;
= {if(!COMMENT)printf("\n\t %s is an ASSIGNMENT OPERATOR",yytext);}
\<= |
\>= |
\< |
== |
\> {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yytext);}
%%
int main(int argc, char **argv)
{
FILE *file;
file=fopen("test.c","r");
if(!file)
{
printf("could not open the file");
exit(0);
}
yyin=file;
yylex();
printf("\n");
return(0);
}
int yywrap()
{
return(1);
}
----------------test c file --------------
#include <stdio.h>
int addition(int num1, int num2)
{
int sum;
// Arguments are used here
sum = num1+num2;
/* Function return type is integer so we are returning
* an integer value, the sum of the passed numbers.
*/
return sum;
}
int main()
{
int var1, var2;
printf("Enter number 1: ");
scanf("%d",&var1);
printf("Enter number 2: ");
scanf("%d",&var2);
/* Calling the function here, the function return type
* is integer so we need an integer variable to hold the
* returned value of this function.
*/
int res = addition(var1, var2);
printf ("Output: %d", res);
return 0;
}
then we have to use the flex tool to compile and generate the lex.yy.c file
the command used is -- flex filename.l
Then compile the lex.yy.c file using the c compiler
It will generate an executable file. Finally, run the executable file. In my case, it is "a.exe" file
Then you will get the desired output.
----- output text ------
#include <stdio.h> is a preprocessor directive
int is a keyword
FUNCTION
addition(
int is a keyword
num1 IDENTIFIER,
int is a keyword
num2 IDENTIFIER
)
BLOCK BEGINS
int is a keyword
sum IDENTIFIER;
//
Arguments IDENTIFIER
are IDENTIFIER
used IDENTIFIER
here IDENTIFIER
sum IDENTIFIER
= is an ASSIGNMENT OPERATOR
num1 IDENTIFIER+
num2 IDENTIFIER;
/* is a COMMENT
return is a keyword
* , .
*/
return is a keyword ;
int is a keyword )
int is a keyword , ;
)
;
;
)
;
;
/* is a COMMENT ,
return is a keyword
*
* .
*/
int is a keyword , )
;
(, )
;
return is a keyword ;
To install c and c++ compiler in windows Click Here.