std :: map错误的多重定义

时间:2016-04-01 21:45:25

标签: c++ dictionary

另外,我正在使用g ++ - 4.9和-std = c ++ 11

进行编译

我在board.h文件中有这个确切的地图:

map <string,string> dirFull = {
    {"no", "north"},
    {"so", "south"},
    {"ea", "east"},
    {"we", "west"},
    {"nw", "north-west"},
    {"ne", "north-east"},
    {"sw", "south-west"},
    {"se", "south-east"},
};

然后我在我的baord.cc文件(即dirFull[no])中的另一个函数中开始使用它,其中包含.h文件。我收到这个错误:

Board/board.o: In function `__gnu_cxx::new_allocator<std::_Rb_tree_node<std::pair<char const, std::string> > >::deallocate(std::_Rb_tree_node<std::pair<char const, std::string> >*, unsigned long)':
/u6/yhavryshchuk/cs246/1161/a5/CC3K/Board/board.cc:11: multiple definition of `dirFull'
main.o:/u6/yhavryshchuk/cs246/1161/a5/CC3K/main.cc:20: first defined here

我找到了这个问题的多个答案,所以我不知道该怎么做。有人说我应该使用extern。有人说声明应该放在.h文件中,但是定义应该放在.cc文件中。

1 个答案:

答案 0 :(得分:3)

dirFull已在board.ccmain.cc中定义(不仅仅是声明)。

您可以使用关键字extern来声明但不是第二次定义相同的变量。

e.g。 extern map<string, string> dirFull;

如果您在另一个编译单元中具有相同的内容,则以下内容将不起作用:

extern map <string,string> dirFull = {
    {"no", "north"},
    {"so", "south"},
    {"ea", "east"},
    {"we", "west"},
    {"nw", "north-west"},
    {"ne", "north-east"},
    {"sw", "south-west"},
    {"se", "south-east"},
};

如您在评论中提到的那样,它会产生dirFull initialized and declared in extern错误。

第一个选项

如果你有base.h例如:

#include <string>
#include <map>

std::map <std::string,std::string> dirFull ={
    {"no", "north"},
    {"so", "south"},
    {"ea", "east"},
    {"we", "west"},
    {"nw", "north-west"},
    {"ne", "north-east"},
    {"sw", "south-west"},
    {"se", "south-east"},
};

然后有Main.cpp

#include "base.h"


extern std::map <std::string,std::string> dirFull;

int main()
{
    dirFull["no"];
}

然后它会起作用。

更好的选择

最好有base.h

#include <string>
#include <map>

extern std::map <std::string,std::string> dirFull;

然后有Main.cpp

#include "base.h"

std::map <std::string,std::string> dirFull ={
    {"no", "north"},
    {"so", "south"},
    {"ea", "east"},
    {"we", "west"},
    {"nw", "north-west"},
    {"ne", "north-east"},
    {"sw", "south-west"},
    {"se", "south-east"},
};

int main()
{
    dirFull["no"];
}

使用最后一个选项,很高兴看到标题中的声明和.cpp(或.cc)文件中的定义。