4

我正在尝试 O'Reilly Flex & Bison 的一些示例。我尝试的第一个 Bison 和 Flex 程序在链接源时给了我下一个错误:

架构 x86_64 的未定义符号:“_yylval”,已引用

从:

  _yylex in lex-0qfK1M.o

由于我是 Mac 新手,我只是在尝试示例,所以我不知道这里出了什么问题。

l 文件:

/* recognize tokens for the calculator and print them out */
%{
#include "fb1-5.tab.h"
%}

%%
"+"     { return ADD; }
"-"     { return SUB; }
"*"     { return MUL; }
"/"     { return DIV; }
"|"     { return ABS; }
[0-9]+  { yylval = atoi(yytext); return NUMBER; }
\n      { return EOL; }
[ \t]   { /* Ignore whitespace */ }
.       { printf("Mystery character %c\n", *yytext); }
%%

y 文件:

/* simplest version of calculator */
%{
#include <stdio.h>
%}
/* declare tokens */
%token NUMBER
%token ADD SUB MUL DIV ABS
%token EOL
%%
calclist: /* nothing */ matches at beginning of input
 | calclist exp EOL { printf("= %d\n", $1); } EOL is end of an expression
 ;
exp: factor default $$ = $1
 | exp ADD factor { $$ = $1 + $3; }
 | exp SUB factor { $$ = $1 - $3; }
 ;
factor: term default $$ = $1
 | factor MUL term { $$ = $1 * $3; }
 | factor DIV term { $$ = $1 / $3; }
 ;
term: NUMBER default $$ = $1
 | ABS term { $$ = $2 >= 0? $2 : - $2; }
 ;
%%
main(int argc, char **argv)
{
    yyparse();
}

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

命令行:

bison -d fb1-5.y
flex fb1-5.l
cc -o $@ fb1-5.tab.c lex.yy.c -ll

我使用 -ll 而不是 -lfl 因为显然在 Mac os x 上, fl 库不存在。

输出:

Undefined symbols for architecture x86_64:
  "_yylval", referenced from:
      _yylex in lex-0qfK1M.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

有任何想法吗?

4

2 回答 2

4

我通过编译一个开始的 lex 文件引起了类似的错误

%{
#include "y.tab.h"
%}

使用命令

gcc -ll lex.yy.c

这有效:

gcc -ll y.tab.c lex.yy.c

这是怎么回事?y.tab.h 中有一个声明

extern int yylval

这允许 lex.yy.c 编译。但是,lex.yy.o 需要链接到包含 yylval 的目标文件,例如 y.tab.o

于 2013-12-03T05:11:32.627 回答
0

显然 O'Reilly 的 Flex & Bison 书充满了错误。

请参阅http://oreilly.com/catalog/errataunconfirmed.csp?isbn=9780596155988

很奇怪,他们甚至不费心测试自己的例子......

部分问题在未定义的对 yyparse (flex & bison) 的引用中得到了解决,但不是全部。请参阅 errataunconfirmed 页面。

于 2013-03-13T11:51:28.297 回答