Windows环境下lex入门

下载部署:

  https://sourceforge.net/projects/winflexbison/ 下载 win_flex_bison-latest.zip ,解压到C:win_flex_bison

编辑lex文件:

  lex文件使用“%%”隔成三个段,分别是:定一段,规则短,用户代码段;

  这里给出一个简单的现成的例子:

%{
int num_lines = 0, num_chars = 0;
%}
%%

      ++num_lines; ++num_chars;
.       ++num_chars;

%%
int yywrap()
{
	return 1;
}
View Code

编译lex文件:

  >c:win_flex_bisonwin_flex.exe --wincompat a.l      // wincompat参数不能省

  没有消息就是好消息,生成了文件 lex.yy.c

导入VS2013项目:

  使用VS2013新建Win32控制台项目

  将lex.yy.c复制到项目下,并改名为 lex.yy.cpp,加入项目

  在头部加入:#include "stdafx.h"

  main函数源文件如下:

// testbench.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stdio.h>

extern int num_lines;
extern int num_chars;
extern FILE *yyin;
extern int yylex(void);

int _tmain(int argc, _TCHAR* argv[])
{
    fopen_s(&yyin, "D:\STUDY\flexbison\linecounter\a.l", "r");
    yylex();
    fclose(yyin);
    printf("lines = %d, chars = %d
", num_lines, num_chars);
    return 0;
}
View Code

  编译运行,大功告成。

原文地址:https://www.cnblogs.com/zhuyingchun/p/9129366.html