94

我有一个简单的“语言”,我正在使用 Flex(词法分析器),它是这样的:

/* 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);
}

我运行 a flex count.l,一切正常,没有错误或警告,然后当我尝试执行 a 时cc lex.yy.c,出现以下错误:

ubuntu@eeepc:~/Desktop$ cc lex.yy.c
/tmp/ccwwkhvq.o: In function yylex': lex.yy.c:(.text+0x402): undefined reference toyywrap'
/tmp/ccwwkhvq.o: In function input': lex.yy.c:(.text+0xe25): undefined reference toyywrap'
collect2: ld returned 1 exit status

怎么了?

4

5 回答 5

144

扫描仪在文件末尾调用此函数,因此您可以将其指向另一个文件并继续扫描其内容。如果您不需要这个,请使用

%option noyywrap

在扫描仪规范中。

尽管禁用yywrap 肯定是最好的选择,但也可以链接到使用flex 提供的库中-lfl的默认函数(即)。Posix 要求该库与链接器标志一起可用,并且默认的 OS X 安装仅提供该名称。yywrap()fllibfl.a-ll

于 2009-11-28T00:42:23.590 回答
13

我更喜欢定义我自己的 yywrap()。我正在使用 C++ 进行编译,但重点应该很明显。如果有人用多个源文件调用编译器,我将它们存储在一个列表或数组中,然后在每个文件的末尾调用 yywrap() 以让您有机会继续使用新文件。

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;
}
于 2014-07-24T04:49:44.137 回答
4

flex 并不总是与它的开发库一起安装(这很奇怪,因为它是一个开发工具)。安装库,生活会更好。

在 Redhat 基本系统上:

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

在基于 Debian 的系统上

sudo apt-get install libfl-dev
于 2016-08-01T15:39:32.703 回答
3

作为关注者的说明,flex 2.6.3 有一个错误,其中 libfl.a “通常会”定义 yywrap 但在某些情况下没有定义,因此请检查这是否是您的 flex 版本,可能与您的问题有关:

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

于 2017-03-09T17:25:36.877 回答
3
int yywrap(){return(1);}

在程序末尾使用此代码..简单

于 2019-02-18T09:53:14.973 回答