升级Ubuntu18.04后Lex/Bison编译报错:yylex未定义引用
undefined reference to 'yylex' Error After Ubuntu 18.04 Upgrade That error is a classic linker issue—let's walk through the most likely fixes, since you already tried make clean and recompiling without luck.
1. Check Your Linker Order in the Makefile
Linker order matters a lot in GCC. If you're linking the flex library (-lfl) before your own object files, the linker won't find yylex (which lives in your lexer-generated code) when it processes libfl.so.
Bad linker command example:
gcc -lfl main.o parser.o lex.yy.o -o gpl
Fixed command:
gcc main.o parser.o lex.yy.o -lfl -o gpl
Make sure all your object files (including the one from your flex-generated .c file) come before -lfl (and -ly if you're using bison) in the linker line of your Makefile.
2. Manually Regenerate Your Flex Lexer
Sometimes after a distro upgrade, the Makefile's dependency rules don't trigger a regeneration of your lexer code. Let's do this manually:
- Navigate to your project directory.
- Run flex on your lexer source file (replace
your_lexer.lwith your actual.lfilename):flex your_lexer.l
This will generate lex.yy.c. Now recompile with make—this ensures you're using a lexer file compatible with the new flex version from Ubuntu 18.04.
3. Verify Your Lexer Object File Is Included in Linking
Double-check that your Makefile is actually compiling and linking the flex-generated object file (usually lex.yy.o). If it's missing from the list of objects in the linker step, the linker has no way to find yylex.
Look for a line in your Makefile like:
OBJECTS = main.o parser.o lex.yy.o
Ensure lex.yy.o is present here.
4. Reinstall Flex to Fix Corrupted or Mismatched Libraries
It's possible the upgrade messed up your flex installation. Reinstall it to ensure you have the correct, uncorrupted version for Ubuntu 18.04:
sudo apt-get install --reinstall flex
This will refresh libfl.so and the flex binaries to match your system's current setup.
5. Check for Flex Version Conflicts
If you had a custom flex installation before the upgrade, it might be conflicting with the system's flex. Run this to check which flex you're using:
flex --version
On Ubuntu 18.04, the expected version is 2.6.4. If you see an older version, adjust your PATH to prioritize the system flex (usually in /usr/bin) over any custom installations.
6. Check for Reentrant Lexer Options
If you're using a reentrant lexer (with %option reentrant in your .l file), yylex isn't a global function anymore—it takes a yyscan_t argument. In this case, you need to make sure your parser (bison) is configured to use the reentrant API, and that you're passing the scanner correctly. If you didn't intend to use reentrancy, remove that option from your lexer file.
内容的提问来源于stack exchange,提问作者Mike1982

