Lex & Yacc 报multiple definition of main错误,求原因与解决方法
Hey there! That multiple definition error for main is super common when working with Lex and Yacc—let me break down what's happening and how to fix it:
What's Causing the Error?
The linker is throwing this error because both lex.yy.o (from your Lex scanner) and y.tab.o (from your Yacc parser) contain a definition of the main function.
By default, Lex generates a basic main function in lex.yy.c that calls yylex() to start scanning. If you've also defined a main function in your Yacc .y file (or Yacc generated one unexpectedly), the linker can't decide which version to use—hence the conflict.
Step-by-Step Fixes
1. Tell Lex not to generate its default main function
Add the %option no-main directive at the very top of your Lex .l file. This tells Lex to skip adding its built-in main, so you can use the main from your Yacc code or a separate file.
Example Lex file start:
%option no-main %option noyywrap # Optional, but avoids another common warning/error /* Your scanner rules here */
2. Check your Yacc .y file for duplicate main
If you've written a custom main in your Yacc file, make sure that's the only one in your codebase. If you didn't write one but Yacc is generating it, double-check your Yacc flags—rare, but some configurations might add a default main (though this is less common than Lex's default).
3. (Best Practice) Move main to a separate C file
For cleaner code separation, create a standalone main.c file that handles starting the parser/scanner. This way, neither Lex nor Yacc generates a main, eliminating the conflict entirely.
Example main.c:
#include <stdio.h> #include "y.tab.h" // Include Yacc-generated header int main() { printf("Starting parser...\n"); yyparse(); // Call Yacc's parser (which calls Lex's scanner internally) return 0; }
Then compile with:
lex scanner.l yacc -d parser.y gcc lex.yy.o y.tab.o main.c -o code_parser
Quick Verification
After making these changes, recompile and link—this should resolve the multiple definition error. If you still run into issues, double-check that no other .c files in your project are defining main accidentally.
内容的提问来源于stack exchange,提问作者구희정학부생

