繁体   English   中英

多个定义?

[英]Multiple definitions?

我在编译flex和bison代码时遇到麻烦。 更具体地说是我的parser.yy文件。 在此文件中,我包含了MathCalc.h和BaseProg.h,它们是我制作的类。 问题是当我实例化类时,它在编译时给我一个“多重定义”错误。 任何帮助,将不胜感激! 谢谢!!

Parser.yy(摘要):

%code requires {
#include <iostream>
#include <cmath>
#include "MathCalc.h"
#include "BaseProg.h"
/* Parser error reporting routine */
void yyerror(const char *msg);

/* Scannar routine defined by Flex */
int yylex();

using namespace std;
BaseProg bprog;
MathCalc calc;

enum Type { INT, FLT};
}
/* yylval union type */
%union {
        double dval;
        int ival;
        char* name;
        Type type;
}

错误:

bison -d parser.yy
g++    -c -o scanner.o scanner.cc
g++    -c -o parser.tab.o parser.tab.cc
g++ scanner.o parser.tab.o BaseProg.o MathCalc.o -lfl -o ../Proj2
parser.tab.o:(.bss+0x0): multiple definition of `bprog'
scanner.o:(.bss+0x28): first defined here
parser.tab.o:(.bss+0x1): multiple definition of `calc'
scanner.o:(.bss+0x29): first defined here
collect2: ld returned 1 exit status

%code requires块中的任何代码都将放置在解析器源文件和解析器头文件中。 这是正常的#include扫描仪源分析器头文件(毕竟,这就是为什么野牛生成一个头文件),所以它是不明智的,把全局变量定义在%code requires块。

确实,将全局变量定义放在头文件中总是不明智的,这恰恰是因为头文件可能包含在多个源文件中,结果是将任何全局定义(而不是声明)都插入到了头文件中。一个以上的翻译单元,违反了ODR。

对于头文件,应将这些对象( BaseProg bprog;MathCalc calc; )标记为extern ,然后确保实际上在某些源文件中定义了它们。 或者,甚至更好的是,您应该首先避免使用全局变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM