c-Flex没有编译词法分析器-宏出错



我用flex编写的词法分析器有问题。当我试图编译它时,没有创建任何exe文件,我得到了很多错误。以下是flex文件:

%{
#ifdef PRINT
#define TOKEN(t) printf("Token: " #t "n");
#else
#define TOKEN(t) return(t);
#endif
%}
delim       [ tn]
ws          {delim}+
digit       [0-9]
id          {character}({character}|{digit})*
number      {digit}+
character   [A-Za-z]
%%
{ws}            ; /* Do Nothing */

":"             TOKEN(COLON);
";"             TOKEN(SEMICOLON);
","             TOKEN(COMMA);
"("             TOKEN(BRA);
")"             TOKEN(CKET);
"."             TOKEN(DOT);
"'"             TOKEN(APOS);
"="             TOKEN(EQUALS);
"<"             TOKEN(LESSTHAN);
">"             TOKEN(GREATERTHAN);
"+"             TOKEN(PLUS);
"-"             TOKEN(SUBTRACT);
"*"             TOKEN(MULTIPLY);
"/"             TOKEN(DIVIDE);
{id}            TOKEN(ID);
{number}        TOKEN(NUMBER);
'{character}'   TOKEN(CHARACTER_CONSTANT);
%%

这些是我收到的错误:

spl.l: In function 'yylex':
spl.l:19:7: error: 'COLON' undeclared (first use in this function)
":"    TOKEN(COLON);
^
spl.l:5:25: note: in definition of macro 'TOKEN'
#define TOKEN(t) return(t);
^
spl.l:19:7: note: each undeclared identifier is reported only once for each function it appears in
":"    TOKEN(COLON);
^
spl.l:5:25: note: in definition of macro 'TOKEN'
#define TOKEN(t) return(t);
^
spl.l:20:7: error: 'SEMICOLON' undeclared (first use in this function)
";"    TOKEN(SEMICOLON);
^
spl.l:5:25: note: in definition of macro 'TOKEN'
#define TOKEN(t) return(t);

我用来编译的命令是:

flex a.l
gcc -o newlex.exe lex.yy.c -lfl

有人能看出我哪里出了问题吗?

您必须首先定义令牌。COLONSEMICOLON等pp的定义(即id)不是由flex生成的。您可以在lexer文件顶部的枚举中定义它:

%{
#ifdef PRINT
#define TOKEN(t) printf("Token: " #t "n");
#else
#define TOKEN(t) return(t);
#endif  
enum { COLON = 257, SEMICOLON, COMMA, BRA, CKET, DOT, APOS, EQUALS,
LESSTHAN, GREATERTHAN, PLUS, SUBTRACT, MULTIPLY, DIVIDE,
ID, NUMBER, CHARACTER_CONSTANT };
%}

我建议ids>257也可以直接从lexer返回ascii字符代码进行进一步处理。然而,通常在yacc/bison的解析器文件中也会使用令牌名称,该解析器文件会生成一个头文件(默认名称为y.tab.h)以包含在lexer中,该头文件包含为那些与解析器函数匹配的令牌生成的id。

最新更新