Oria Gruber
Oria Gruber

Reputation: 1533

flex - no entry point

I'm studying compilation theory and how to work with flex and i have several issues.

I created a lex file with the following data in it:

%%
"hello"     printf("GOODBYE");
.   ;
%%

This is the simplest one I could think of. If I understand correctly, it prints GOODBYE every time it encounters the hello token, and ignores everything else.

I used flex on this lex file to generate a C file, and I should now compile that C code to get the lexical analyzer for this grammar.

The problem is that the generated C code has no entry point. It does not compile. Is my .lex file incorrect? Am I misunderstanding something?

Upvotes: 0

Views: 167

Answers (2)

John Bollinger
John Bollinger

Reputation: 180058

The problem is that the generated C code has no entry point. It does not compile.

No, it does not link.

Is my .lex file incorrect?

No.

Am I misunderstanding something?

Yes.

An "entry point" is the linker's way of saying function main(). Flex generates code for only a lexical analyzer function, so if you want a complete program then you need to provide main separately. This is appropriate because most often, the lexer function is used in the context of a larger program, where the lexer function is the only thing needed or wanted from Flex.

If everything you want the program to do is describe by your lexical analysis rules then you want a main function that repeatedly calls the lexical analysis function, yylex(), until it return non-zero. You can write your own, but you do not need to do -- flex comes with a runtime library, libfl, whose primary purpose is to provide exactly such a main. You just need to link it in, probably by adding -lfl to the end of you compilation / link command.

Upvotes: 1

komar
komar

Reputation: 881

You need just declare own main() in this file, after second %% or link this .c with other .c file where main() declareted.

%%
"hello"     printf("GOODBYE");
.   ;
%%

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

Upvotes: 2

Related Questions