lex与yacc之lex初探

这是个简单的单词识别程序,虽然小,但依然体现出lex的强大之处。
lex自动生成实际的C程序代码,这些代码负责处理读输入文件,有时也负责写输出。

verb.l


第一部分为定义部分,介绍了将拷贝到最终程序中的原始C程序代码。如果后来文件中的代码必须包含的头文件,那么这部分尤其重要。用特殊的定界符"%{"和"%}"括起C代码。这个示例中,定义段中唯一的内容是C注释。

%%标记这一部分结束。
下一部分是规则段。每个规则段都有两部分组成:模式和动作,由空白分开。当lex生成的词法分析程序识别出某个模式时,将执行相应的动作。这些模式是UNIX样式的正则表达式。
yytext数组包含匹配模式的文本。这个动作将打印出识别出的动词,后跟字符串":is a verb/n"
规则段的结尾以另一个%%来界定。
最后的部分是用户子例程段,由任意合法的C代码组成。在lex生成代码后结束之后,lex将它复制到C文件。我们已经包含了一个main()例程。
%%
main()
{
 yylex();
}

用cygwin生成编译:
flex verb.l
cc lex.yy.c -o first

执行
$ ./first
This is a pig
This: is not a verb
is: is a verb
a: is not a verb
pig: is not a verb
^D结束执行

关于定义
int yywrap()
{
    return 1;
}
的目的,如果不实现该函数,会出现错误
undefined reference to `_yywrap'
以下是在网上转载的解决方法:
可以在lex.c加入如下的行来解决问题。
#define yywrap()  1

更好的办法是定义:
int yywrap()
{
   return(1);
}

关于yywrap更详细的信息可以参考unix的lex manual
http://www.scit.wlv.ac.uk/cgi-bin/mansec?1+lex

int yywrap(void)
           Called by yylex at  end-of-file;  the  default  yywrap
           always  will  return  1.  If  the application requires
           yylex to continue processing with  another  source  of
           input,  then  the  application  can include a function
           yywrap, which associates another file with the  exter-
           nal  variable  FILE  *yyin  and will return a value of
           zero.

或flex的参考手册(这个貌似更广泛一点):
http://www.gnu.org/software/flex/manual/html_mono/flex.html


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 condition remains unchanged; it does not revert to INITIAL.

If you do not supply your own version of `yywrap()', then you must either use `%option noyywrap' (in which case the scanner behaves as though `yywrap()' returned 1), or you must link with `-lfl' to obtain the default version of the routine, which always returns 1.

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值