未定义的对 yywra 的引用

我有一个简单的“语言”,我正在使用 Flex (Lexical Analyzer) ,它是这样的:

/* Just like UNIX wc */
%{
int chars = 0;
int words = 0;
int lines = 0;
%}


%%
[a-zA-Z]+ { words++; chars += strlen(yytext); }
\n        { chars++; lines++; }
.         { chars++; }
%%


int main()
{
yylex();
printf("%8d%8d%8d\n", lines, words, chars);
}

我运行一个 flex count.l,没有错误或警告,一切都很好,然后当我尝试做一个 cc lex.yy.c我得到了这个错误:

Ubuntu@eeepc: ~/Desktop $cc lex.yy.c
/tmp/ccwwkhvq.o: 在函数 < code > yylex’中: C: (. text + 0 x402) : 对 yywra’< br/> 的未定义引用 /tmp/ccwwkhvq.o: 在函数 < code > input’: C: (. text + 0 xe25) : 对 yywra’< br/> 的未定义引用 Collect2: ld 返回1退出状态

怎么了?

77647 次浏览

The scanner calls this function on end of file, so you can point it to another file and continue scanning its contents. If you don't need this, use

%option noyywrap

in the scanner specification.

Although disabling yywrap is certainly the best option, it may also be possible to link with -lfl to use the default yywrap() function in the library fl (i.e. libfl.a) provided by flex. Posix requires that library to be available with the linker flag -ll and the default OS X install only provides that name.

I prefer to define my own yywrap(). I'm compiling with C++, but the point should be obvious. If someone calls the compiler with multiple source files, I store them in a list or array, and then yywrap() is called at the end of each file to give you a chance to continue with a new file.

int yywrap() {
// open next reference or source file and start scanning
if((yyin = compiler->getNextFile()) != NULL) {
line = 0; // reset line counter for next source file
return 0;
}
return 1;
}

flex doesn't always install with its development libraries (which is odd, as it is a development tool). Install the libraries, and life is better.

On Redhat base systems:

yum -y install flex-devel
./configure && make

On Debian based systems

sudo apt-get install libfl-dev

As a note for followers, flex 2.6.3 has a bug where libfl.a "typically would" define yywrap but then doesn't in certain instances, so check if that's your version of flex, might be related to your problem:

https://github.com/westes/flex/issues/154

int yywrap(){return(1);}

use this code at the end of the program..Simple