gpt4 book ai didi

c++ - std::map 错误的多重定义

转载 作者:行者123 更新时间:2023-11-28 00:04:49 24 4
gpt4 key购买 nike

此外,我正在使用 g++-4.9 和 -std= c++11 进行编译

我的 board.h 文件中有这张精确的 map :

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 文件中。

最佳答案

dirFullboard.cc 中都定义(不仅仅是声明)和 main.cc .

您可以使用关键字 extern声明,但不是第二次定义同一个变量。

例如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"];
}

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

关于c++ - std::map 错误的多重定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36366343/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com