You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Flex解析.l文件时链接报错:undefined reference to `main'

Flex编译报错:undefined reference to `main'

我的Flex代码(scanner.l)

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

%%
[ \t\n]          /* ignore whitespace */
"MATCH"          { return MATCH; }
"RETURN"         { return RETURN; }
"-"              { return DASH; }
"("              { return LPAREN; }
")"              { return RPAREN; }
"["              { return LBRACKET; }
"]"              { return RBRACKET; }
[uv]             { return VARIABLE; }
%%
int yywrap(void) {
    return 1;
}

编译错误信息

/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/11/../../../x86_64-linux-gnu/Scrt1.o: in function `_start':
(.text+0x1b): undefined reference to `main'
collect2: error: ld returned 1 exit status

问题原因及解决方法

这个错误的核心是:Flex生成的扫描器代码本身没有包含main函数,而C程序必须有main作为入口点。结合你代码里引用了main.tab.h,推测你是在和Bison(语法分析器)配合使用,以下分两种场景解决:

场景1:与Bison配合使用

  1. 先确保你已经用Bison生成了语法分析器代码:
    执行命令生成main.tab.c和main.tab.h:
    bison -d main.y
    
  2. 编译时把Flex生成的扫描器代码、Bison生成的语法分析器代码一起编译,同时链接Flex的库:
    flex scanner.l
    gcc lex.yy.c main.tab.c -o parser -lfl
    

场景2:单独测试Flex扫描器

如果只是想单独测试扫描功能,直接在你的Flex代码末尾添加main函数:

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

%%
[ \t\n]          /* ignore whitespace */
"MATCH"          { return MATCH; }
"RETURN"         { return RETURN; }
"-"              { return DASH; }
"("              { return LPAREN; }
")"              { return RPAREN; }
"["              { return LBRACKET; }
"]"              { return RBRACKET; }
[uv]             { return VARIABLE; }
%%
int yywrap(void) {
    return 1;
}

// 添加main函数
int main() {
    yylex();
    return 0;
}

然后重新编译:

flex scanner.l
gcc lex.yy.c -o scanner -lfl

内容的提问来源于stack exchange,提问作者fatima raza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 05:43:20