I'm doing an assignment on compiler. So I have three files. A SymbolInfo.h
file, a parser.y
file and a lex.l
file.
SymbolInfo.h
file:
<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_ */
I need to initialize the static variable id
. So I first tried to initialize it in the .h
file:
int SymbolTable::id = 0;
#endif /* SYMBOLINFO_H_ */
Then when I tried to compile it but it gives the following compilation error:
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
So I removed the initialization from the .h
file and moved them to .l
and .y
file.
The .y
file:
%{
<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);
%}
And the .l
file:
%{
<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;
......
%}
But it still gives the same error and I'm not understanding why. Sorry for the long post, but any help would be appreciated.
script.sh
file for compilation commands:
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
Link to full code:
If you look, you will see how both the .y
and .l
file work together. You will see how variables defined in one are marked as extern
in the other and vice versa. This is because both output .c
files. If they both include the static variable definition and then are compiled and linked, you get the "multiple definition" error.
To fix this, put the initialization in only one of the two files.