链接器在标头中为 std::map 失败
Linker fails for std::map in header
我正在尝试使用code::blocks和mingw创建一个简单的c ++程序,并且遇到了某种链接错误。 当我尝试构建项目时,ld 返回 1,没有其他详细信息。 我尝试在网上搜索有关此类问题的信息,但找不到任何内容。
我尝试将example
的定义从test.hpp
移动到test.cpp
,这确实解决了链接问题,但它使我无法访问example
从其他导入test.hpp
的文件。 我也尝试完全删除命名空间,但出于组织原因,我想避免这种情况(如果这是命名空间的完全不恰当的使用,我将不胜感激(。 我正在尝试使我的程序的几个部分最终能够在运行时访问和更新example
。
测试.hpp
#include <map>
#include <string>
namespace testing{
std::map<std::string,int> example;
}
测试.cpp
#include "test.hpp"
#include <iostream>
namespace testing {
std::map<std::string,int> example;
}
构建输出
=== Build: Debug in SilhouetteEngine (compiler: GNU GCC Compiler) ===
error: ld returned 1 exit status
=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===
某处应该有一个更全面的构建日志,其中会说testing::example
被多次定义。
解决方案很简单:仅使用 extern
关键字在头文件中声明变量:
// In header file
namespace testing{
extern std::map<std::string,int> example;
}
你的头和 cpp 都定义了你的变量example
。您应该将标头中的变量声明为 extern
。
如何使用 extern 在源文件之间共享变量?
相关文章:
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 使用一个考虑到std::map中键值的滚动或换行的键
- 有没有办法对std::unordered_set、std::unrdered_map、std::set、std::map
- 将重物插入std::map
- 使用通用值初始化 std::map,不重复
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- C++:当所有条目都保证是唯一时,替代 std::map
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- C++如何创建 std::map
- 从其他容器中移动构造"std::map"
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- C++中 std::map 的运行时复杂度是多少?
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 使用重载 [] 运算符返回 std::map() 的可赋值
- std::map, std::unordered_map - 缩小初始值设定项列表中的转换范围
- C++ 使用枚举类对象分配 std::map 值
- 静态 std::map instatiation 在类的方法中调用构造函数吗?
- std::map:当元素不可默认构造时创建/替换元素
- Arduino编译器和STL:使用std::vector和std::map