1

I'm trying to make a lexical analyzer using flex. For convenience, I want to compile my scanner.l to lex.yy.cc, and then compile the .cc file by command: g++ lex.yy.cc -lfl.

The -lfl is required. The g++ then gave me following error message: undefined reference to 'yylex' Here is the briefly snapshot of my scanner.l

%{
...
#include ...
extern "C" int yylex();
...
%}
...
%option c++
%option noyywrap

%%
/* rules */
%%

I have done some study, stack overflow says it should be fixed by adding extern "C" int yylex();. However, it did not.

I am using flex 2.6.4 on a remote(from school) linux machine. enter image description here

林子嵎
  • 25
  • 4

1 Answers1

2

TL;DR: remove %option c++.


The -lfl is required.

Are you sure? libfl provides only two functions: yywrap(), which you do not need because of

%option noyywrap

, and main(), which you do not need if you provide your own main(). The main() in libfl just calls yylex() over and over until the latter signals end-of-input, which is surely where the depency on yylex() is coming from in your case.

If you have some external requirement to rely on libfl for your program's main, then you have shot yourself in the foot by specifying

%option c++

. That option is more about the API the generated scanner will provide than about the language that will be used to compile it. You do need to compile as C++ if you use it, but you can still compile as C++ if you don't. You should omit that option to have yylex() as the scanner entry point.

Declaring C linkage for yylex() is what you do if you plan to omit %option c++, compile with a C++ compiler, and link with other code (such as libfl) that expects the C interface for yylex(). But it is rare for that to be an advantageous combination, because the kinds of actions a typical scanner wants to perform don't gain much from C++ relative to C. Thus, if you want the C interface to yylex() then it is usually cleaner to just write the actions in C and compile the scanner with a C compiler. And of course, you can still call that from C++ if you like.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157