C++ 静态类变量的多重定义
我正在做一个关于编译器的作业。所以我有三个文件。一个C++ 静态类变量的多重定义,c++,bison,lex,C++,Bison,Lex,我正在做一个关于编译器的作业。所以我有三个文件。一个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;
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_ */
int SymbolTable::id = 0;
#endif /* SYMBOLINFO_H_ */
%{
<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);
%}
%{
<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;
......
%}
然后当我试图编译它时,它给出了以下编译错误:
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
文件:
<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_ */
int SymbolTable::id = 0;
#endif /* SYMBOLINFO_H_ */
%{
<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);
%}
%{
<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
文件。如果它们都包含静态变量定义,然后被编译和链接,则会出现“多重定义”错误
要解决此问题,请仅将初始化放在两个文件中的一个文件中。您需要将初始化行正好放在一个文件中。我不知道.l和.y文件是如何使用的,所以我不能给你一个正确的答案。从你发布的内容来看,你的标题可能丢失了。编辑:点击链接;有卫兵,但为什么他们在包内?至少看起来是件奇怪的事。谢谢。它解决了问题!我应该更小心一点。