Use of int main() in flex file

149 Views Asked by At

Consider a flex file file1.l

%{
int count = 0;
%}

%%
[A-Z]* { printf("%s is a capital letter string \n", yytext);
        count++; }
.     { printf("%s not a capital letter\n", yytext); }
\n    { return 0; }
%%

int main(){
  yylex();
  return 0;
}

Consider another flex file file2.l

%{
int count = 0;
%}

%%
[A-Z]* { printf("%s is a capital letter string \n", yytext);
        count++; }
.     { printf("%s not a capital letter\n", yytext); }
\n    { return 0; }
%%

Note that file1.l and file2.l differ only in int main() part. We use following commands on both the files.

flex filename.l
gcc -o filename.exe lex.yy.c -lfl
./filename.exe

I observed that both the files gets executed the same way. Why is that? Does that mean int main() doesnot have any role?

1

There are 1 best solutions below

0
rici On

There is nothing special about flex. This is just the result of linking with -lfl.

libfl contains a default implementation of main(). Like any member of a library archive, the definition of main() in a linked library will be used if needed. If you supply a definition in an object file, the archive member won't be used.

So your definition of main() is the one which is used in the case of file1. It differs from the one on libfl in that yours only calls yylex() once whereas the libfl definition calls yylex() in a loop until it returns 0.

libfl also contains a default implementation of yywrap(); again, it will be used only if needed. (In your examples, yywrap() is needed because you don't define it. Use %option noyywrap to remove the dependency.)

If you don't need these default definitions, linking with -lfl is unnecessary.

Both if these library members are specified by the Posix standard for lex (although in Posix the library is linked with -ll).