您的位置:首页 > 其它

从自己的程序中使用lex的一个小例子

2013-05-17 12:03 706 查看
网上很多例子,都是yacc和lex结合的。而我想找一个单纯使用 lex的例子。而且可以从我的主程序来调用它。

上程序:

第一步,编写 flex 文件:example.flex

从网上找到的,其功能是对行数和字符数计数。

[root@cop01 tst]# cat example.flex
/* name: example.flex */
%option noyywrap
%{
int num_lines =0, num_chars=0;
%}
%%

\n ++num_lines; ++num_chars;
. ++num_chars;

%%

int counter(char *stream,int *nlines,int *nchars)
{
yy_scan_string("a test string\n\n");
yylex();
*nlines=num_lines;
*nchars=num_chars;
return 0;

}
[root@cop01 tst]#


这里,在flex文件中,我没有声明main方法,即使声明了,也会生成在 flex example.flex 后得到的 lex.yy.c 中。

而我想要从我自己的程序里,来调用,所以命名了这个counter函数。

要特别注意上面的 yy_scan_string函数调用,如果没有对它的调用,yylex会从标准输入来读信息流的。

第二步,编写我的主程序:

[root@cop01 tst]# cat test.c
#include <stdio.h>
#include "test.h"

int main()
{
char cstart[50]="This is an example\n\n";
int plines=0;
int pchars=0;
counter(cstart,&plines,&pchars);

fprintf(stderr,"lines counted: %d \n",plines);
fprintf(stderr,"chars counted: %d \n",pchars);

return 0;
}
[root@cop01 tst]#


第三步,编写头文件:

[root@cop01 tst]# cat test.h
int counter(char *stream,int *nlines,int *nchars);
[root@cop01 tst]#


最后,进行编译和运行:

[root@cop01 tst]# gcc -g -Wall -c lex.yy.c
lex.yy.c:974: warning: ‘yyunput’ defined but not used
[root@cop01 tst]# gcc -g -Wall -c test.c
[root@cop01 tst]# gcc -g -Wall -o test test.o lex.yy.o
[root@cop01 tst]# ./test
lines counted: 2
chars counted: 15
[root@cop01 tst]#


结束!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐