c - undefined reference 'yylex' bison 错误

标签 c bison flex-lexer

嗨,我是 bison 和 flex 的新手,我正在尝试创建一个简单的计算器,但是在尝试编译时似乎遇到了错误。

以下是我的 flex .l 文件(名为 a.l):

%{
#include "a.tab.h"
%}
number  [0-9]+

%%

"+"     {return ADD;}
"-"     {return SUB;}
"*"     {return MUL;}
"/"     {return DIV;}
"|"     {return ABS;}
{number}     { return NUMBER;}
\n      {return EOF;}
[ \t]   { }
.    {printf("Mystery Character %s\n", yytext); }

%%

以下是我的 bison .y 文件(名为 a.y):

%{
#include <stdio.h>
int yyparse(void);
%}

%token NUMBER ADD SUB MUL DIV ABS EOL

%%

calclist: /*nothing*/ | calclist exp EOL { printf("=%d\n, $1") };

exp: factor
    | exp ADD factor { $$ = $1 + $3; }
    | exp SUB factor { $$ = $1 - $3; }
    ;

factor: term |
        | factor MUL term { $$ = $1 * $3; }
        | factor DIV term { $$ = $1 / $3; }

term: NUMBER
    | ABS term { $$ = $2 >= 0? $2 : - $2; }
    ;

%%

int main(void)
{
    return(yyparse());
}

void yyerror(char *s)
{
    fprintf(stderr, "Error : Exiting %s\n", s);
}

这是我在控制台中写的内容:

flex a.l
bison a.y
gcc a.tab.c -lfl -o a.exe

我得到的错误是:

a.tab.c:(.text+0x1f2): undefined reference to `yylex'
collect2.exe: error: ld returned 1 exit status

我还收到以下警告:

a.tab.c: In function 'yyparse':
a.tab.c:595:16: warning: implicit declaration of function 'yylex' [-Wimplicit-function-declaration]
# define YYLEX yylex ()
               ^
a.tab.c:1240:16: note: in expansion of macro 'YYLEX'
       yychar = YYLEX;
                ^~~~~
a.tab.c:1396:7: warning: implicit declaration of function 'yyerror' [-Wimplicit-function-declaration]
       yyerror (YY_("syntax error"));
       ^~~~~~~
a.y: At top level:
a.y:32:6: warning: conflicting types for 'yyerror'
 void yyerror(char *s)
      ^~~~~~~
a.tab.c:1396:7: note: previous implicit declaration of 'yyerror' was here
       yyerror (YY_("syntax error"));
       ^~~~~~~

有人可以向我解释为什么会发生这些错误/警告吗?

最佳答案

将生成两个 C 文件,一个由 flex 生成,另一个由 bison 生成。由 flex 创建的文件名为“lex.yy.c”,您还需要编译该文件。

关于c - undefined reference 'yylex' bison 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46778423/

相关文章:

c - free() 上的段错误

c - 与 omp atomic 并行化

parsing - 在Bison错误后如何跳过一行中的其余 token

parsing - jison语法定义导致token识别错误

c - Eclipse 转到标签在 C 中不起作用

macos - 为什么我的 Mac (OS X 10.7.3) 有一个旧版本 (2.3) 的 Gnu Bison?

c - 如何用 Bison 返回函数名?

variables - Flex/Lex - 如何知道变量是否已声明

c - Flex 启动条件意外结果

c - 用 C 代码实现哥德巴赫猜想