tags:

views:

198

answers:

3

When I attempt to compile the output of this trivial lex program:

# lex.l
integer   printf("found keyword INT");

using:

$ gcc lex.yy.c

I get:

Undefined symbols:
  "_yywrap", referenced from:
      _yylex in ccMsRtp7.o
      _input in ccMsRtp7.o
  "_main", referenced from:
      start in crt1.10.6.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

lex --version tells me I'm actually using 'flex 2.5.35' although ls -fla `which lex` isn't a symlink. Any ideas why the output won't compile?

A: 

You're trying to compile it into an executable (this is what the gcc call does without flags), so the linker is looking for a main function and yywrap. Do you have those functions available in your .l file?

gcc -c lex.yy.c

Has a better chance of working since it's only creating the object file.

I suggest you go by a tutorial of Lex to know which files & functions are needed for a basic hello-world functionality. Generally, yywrap usually suffices, and main of course.

Eli Bendersky
I would love to hear the reason for the downvoting of this answer
Eli Bendersky
Downvoting seems unfair, although it's not a particularly striking answer.
Kinopiko
@Kinopiko: I'm not sure what "striking" means in this context, but I think it answers the OP's problem
Eli Bendersky
Agreed. Downvotes should be reserved for incorrect or misleading answers -- that is, answers which are actually wrong. If you think it's simply not a particularly good right answer, then don't upvote it.
Brooks Moses
I agree with you that it answers the question.
Kinopiko
+1  A: 

As Eli's answer implies, that's not a trivial lex program. It's a trivial lex file, and thus a portion of a program, but it (like any lex file) needs to be combined with some C code to make a complete program. In particular, you still need a main function (which you write in C or C++ or something, in a separate file), and you will also need to write a yywrap function that provides the interface between the lex code and the rest of your C code.

Brooks Moses
+3  A: 

From the Flex manual:

I get an error about undefined yywrap().

You must supply a yywrap() function of your own, or link to libfl.a (which provides one), or use

 %option noyywrap

in your source to say you don't want a yywrap() function.

Also:

When the scanner receives an end-of-file indication from YY_INPUT, it then checks the yywrap() function. If yywrap() returns false (zero), then it is assumed that the function has gone ahead and set up yyin to point to another input file, and scanning continues. If it returns true (non-zero), then the scanner terminates, returning 0 to its caller. Note that in either case, the start condi- tion remains unchanged; it does not revert to INITIAL.

Kinopiko
+1 for mentioning linking with libfl.a, which provides a trivial `main()` as well as `yywrap()`: just build using `$ gcc lex.yy.c -lfl`.
Matthew Slattery