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

网上很多例子,都是yacc和lex结合的。而我想找一个单纯使用 lex的例子。而且可以从我的主程序来调用它。

上程序:

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

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

 1 [root@cop01 tst]# cat example.flex
 2 /* name: example.flex */
 3 %option noyywrap
 4 %{
 5 int num_lines =0, num_chars=0;
 6 %}
 7 %%
 8 
 9 \n ++num_lines; ++num_chars;
10 . ++num_chars;
11 
12 %%
13 
14 int counter(char *stream,int *nlines,int *nchars)
15 {
16   yy_scan_string("a test string\n\n");
17   yylex();
18   *nlines=num_lines;
19   *nchars=num_chars;
20   return 0;
21 
22 }
23 [root@cop01 tst]# 

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

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

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

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

 1 [root@cop01 tst]# cat test.c
 2 #include <stdio.h>
 3 #include "test.h"
 4 
 5 int main()
 6 {
 7   char cstart[50]="This is an example\n\n";
 8   int plines=0;
 9   int pchars=0;
10   counter(cstart,&plines,&pchars);
11  
12   fprintf(stderr,"lines counted: %d \n",plines);
13   fprintf(stderr,"chars counted: %d \n",pchars);
14 
15   return 0;
16 }
17 [root@cop01 tst]# 

第三步,编写头文件:

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

最后,进行编译和运行:

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

结束!