【发布时间】:2017-06-08 05:47:57
【问题描述】:
我有这些文件:
main.cpp
headers.h
calculator.h
calculator.cpp
Supported_operators.h
Supported_operators.c
My_Operations.h
My_Operations.cpp
我的headers.h 文件有(除了标准库):#include "Supported_operators.h",最后我的Supported_operators.h 有以下内容:
#ifndef CALCULATOR_SUPPORTED_OPERATORS_H
#define CALCULATOR_SUPPORTED_OPERATORS_H
#include "headers.h"
//using directives
class Supported_operator {
//stuff
};
list<Supported_operator> supportedOps = {
Supported_operator('+', 2, 'l'),
Supported_operator('-', 2, 'l'),
Supported_operator('*', 3, 'l'),
Supported_operator('/', 3, 'l'),
Supported_operator('^', 4, 'r')
};
#endif //CALCULATOR_SUPPORTED_OPERATORS_H
当我尝试编译程序时,编译器在我的main() 上显示multiple definition of supportedOps[abi:cxx11]。
我该如何解决这个问题?
上下文:我正在尝试制作一个计算器。必须将string 输入拆分为令牌。如果 token 是运算符,则根据该运算符执行某些操作。所以我必须创建一个SupportedOperators 的容器,然后检查是否支持标记运算符以及它的属性是什么。
编辑 2: 我的 headers.h 文件现在包含 const list<Supported_operator> supportedOps; 和我的 Supported_operators.cpp 现在有 list<Supported_operator> supportedOps = { }; 但随后 headers.h 触发错误 list does not name a type。
编辑 3: 将 headers.h 中的声明更改为 extern const std::list<> supportedOps; 现在会导致一组新错误 - Supported_operator 未在该范围内声明。我以为我已经用#include "Supported_operators.h 覆盖了它,其中声明了Supported_operator。我是否正确地假设编译器还不知道 Supported_operator 类?我该如何解决这个问题?
【问题讨论】:
-
list<Supported_operator> supportedOps- 那个东西属于翻译单元(即cpp文件)和标题中的extern,或匿名命名空间,或 作为static.
标签: c++ multiple-definition-error