header 中的 std::map 链接器失败

Linker fails for std::map in header

我正在尝试使用 code::blocks 和 mingw 创建一个简单的 c++ 程序,但我遇到了某种链接错误。当我尝试构建项目时,ld returns 1 没有其他详细信息。我曾尝试在网上搜索有关此类问题的信息,但一直找不到任何信息。

我尝试将 example 的定义从 test.hpp 移动到 test.cpp,这确实解决了链接问题,但它使我无法访问 example 来自导入 test.hpp 的其他文件。我也尝试过完全删除命名空间,但出于组织原因我想避免这样做(如果这是对命名空间的完全不恰当的使用,我将不胜感激)。我正在努力做到这一点,以便最终我的程序的几个部分能够在运行时访问和更新 example

test.hpp

#include <map>
#include <string>

namespace testing{

    std::map<std::string,int> example;

}

test.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;
}

你的 header 和 cpp 都定义了你的变量 example。您应该将 header 中的变量声明为 extern

How do I use extern to share variables between source files?