Xubuntu环境下Flex与Bison编译报错问题求助
问题分析与解决
1. 链接错误:/usr/bin/ld: cannot find -ly: No such file or directory
原因:-ly是用于链接传统Bison库的参数,但你使用的GNU Bison 3.8.2属于现代版本,生成的解析器代码已内置所需函数,不再依赖该库;同时Ubuntu系统默认未安装liby-dev包,也是找不到库的直接原因。
解决:编译命令中移除-ly参数,修改后的命令为:
gcc lex.yy.c test.tab.c -o test -L/usr/lib -lfl
2. 隐式声明警告:implicit declaration of function ‘yylex’
原因:Bison生成的test.tab.c中调用了yylex(),但未提前声明该函数。Flex生成的lex.yy.c虽定义了yylex,但Bison代码中无对应声明,导致GCC触发隐式声明警告。
解决:任选一种方式即可:
- 方式一:在
test.y的%{与%}代码块中添加yylex声明:%{ extern int yylex(); %} - 方式二:生成Flex头文件并在Bison中引用。执行Flex时增加参数:
再在flex --header-file=lex.yy.h test.ltest.y的%{块中添加:#include "lex.yy.h"
3. 隐式声明警告:implicit declaration of function ‘yyerror’
原因:Bison默认会调用yyerror()输出语法错误信息,但你未定义或声明该函数。
解决:在test.y的%{与%}代码块中添加yyerror的定义:
%{ #include <stdio.h> void yyerror(const char *msg) { fprintf(stderr, "Error: %s\n", msg); } %}
完整操作流程
- 修改
test.y文件,补充上述必要声明与函数定义; - 重新执行生成与编译命令:
flex test.l # 若用方式二则执行 flex --header-file=lex.yy.h test.l bison -d test.y gcc lex.yy.c test.tab.c -o test -L/usr/lib -lfl
内容的提问来源于stack exchange,提问作者Zizou Amgh
相关产品推荐
相关产品推荐

