我正在做编译器的作业。所以我有三个文件。SymbolInfo.h
文件、parser.y
文件和lex.l
文件。
SymbolInfo.h
文件:
<include files....>
using namespace std;
#ifndef SYMBOLINFO_H_
#define SYMBOLINFO_H_
<more code...>
class SymbolTable{
static int id;
int bucket;
ScopeTable* parentScope;
<constructors and methods....>
}
#endif /* SYMBOLINFO_H_ */
我需要初始化静态变量id
。所以我首先尝试在.h
文件中初始化它:
int SymbolTable::id = 0;
#endif /* SYMBOLINFO_H_ */
然后当我尝试编译它时,它给出了以下编译错误:
l.o:(.bss+0x28): multiple definition of `SymbolTable::id'
y.o:(.bss+0x0): first defined here
l.o:(.bss+0x30): multiple definition of `id'
y.o:(.bss+0x430): first defined here
collect2: error: ld returned 1 exit status
./script.sh: line 14: ./a.out: No such file or directory
所以我从.h
文件中删除了初始化,并将它们移动到.l
和.y
文件中。
.y
文件:
%{
<some include files>
#include "SymbolInfo.h"
int SymbolTable::id = 0;
#define YYSTYPE SymbolInfo*
using namespace std;
int yyparse(void);
int yylex(void);
extern FILE *yyin;
extern int line_count;
FILE *fp;
ofstream logout,errorout;
const int bucketSize = 10;
SymbolTable symbolTable(bucketSize);
%}
和.l
文件:
%{
<some include files...>
#include "SymbolInfo.h"
int SymbolTable::id = 0;
#include "y.tab.h"
using namespace std;
int line_count = 1;
int TOTAL_ERROR = 0;
extern SymbolTable symbolTable;
extern FILE *yyin;
extern YYSTYPE yylval;
extern ofstream logout,errorout;
......
%}
但它仍然给出同样的错误,我不明白为什么。很抱歉这篇文章很长,但任何帮助将不胜感激。
编译命令的script.sh
文件:
bison -d -y -v parser.y
g++ -std=c++11 -w -c -o y.o y.tab.c
flex "Lexical Analyzer".l
g++ -std=c++11 -w -c -o l.o lex.yy.c
g++ -std=c++11 -o a.out y.o l.o -lfl -ly
./a.out
链接到完整代码:
弹性文件
野牛文件
符号表
如果你看一下,你会看到.y
和.l
文件是如何协同工作的。您将看到一个变量中定义的变量如何在另一个中标记为extern
变量,反之亦然。这是因为输出.c
文件。如果它们都包含静态变量定义,然后被编译和链接,则会出现"多重定义"错误。
要解决此问题,请仅将初始化放在两个文件中的一个中。