使用g++编译.l文件时出现LETTER/DIGIT未声明作用域错误求助
解决Lex中DIGIT和LETTER未声明的错误
问题
编译Lex生成的C代码时出现以下错误:
‘LETTER’ was not declared in this scope‘DIGIT’ was not declared in this scope
用户提供的Lex代码如下:
%option noyywrap %{ int mylineno = 0; %} %% [ \t\n] ; [0-9]* { return DIGIT;} [a-zA-Z]* { return LETTER; } . { puts('Syntax Error'); } %% #include<iostream> using namespace std; int main(int, char**) { // open a file handle to a particular file: FILE *myfile = fopen("/SOURCE/MAIN.mave", "r"); // make sure it's valid: if (!myfile) { cout << "I can't open MAIN.mave!" << endl; return -1; } // set lex to read from it instead of defaulting to STDIN: yyin = myfile; // lex through the input: while(yylex()); }
错误原因
Lex不会自动定义DIGIT、LETTER这类标识符,它们并非Lex的内置常量。你需要手动声明这些符号,或者直接返回数值。
解决方案
方式1:预定义常量
在开头的%{...%}代码块中,用#define或者const声明这两个常量:
%{ int mylineno = 0; #define DIGIT 1 #define LETTER 2 %}
或者使用const变量:
%{ int mylineno = 0; const int DIGIT = 1; const int LETTER = 2; %}
方式2:直接返回数值
如果不需要命名常量,也可以直接在动作中返回数字:
[0-9]* { return 1;} [a-zA-Z]* { return 2; }
额外注意
代码中puts('Syntax Error');存在错误:单引号用于单个字符,字符串需要用双引号,应修改为:
. { puts("Syntax Error"); }
内容的提问来源于stack exchange,提问作者user17534832
相关产品推荐
相关产品推荐

