【问题标题】:Linker fails for std::map in header标头中的 std::map 链接器失败
【发布时间】:2017-10-22 22:34:29
【问题描述】:

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

我尝试将example 的定义从test.hpp 移动到test.cpp,这确实解决了链接问题,但它使我无法从导入@987654325 的其他文件中访问example @。我也尝试过完全删除命名空间,但出于组织原因,我想避免这种情况(如果这是对命名空间的完全不恰当使用,我会很高兴知道)。我正在努力做到这一点,以便最终我的程序的几个部分能够在运行时访问和更新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)) ===

【问题讨论】:

    标签: c++ mingw std ld stdmap


    【解决方案1】:

    应该有一个更全面的构建日志,它会说testing::example被定义了多次。

    解决方法很简单:只声明头文件中的变量,使用extern关键字:

    // In header file
    namespace testing{
        extern std::map<std::string,int> example;
    }
    

    【讨论】:

    • 谢谢,距离上一次学习c++课程已经很久了,我完全忘记了extern
    【解决方案2】:

    您的标头和 cpp 都定义了您的变量 example。您应该在标题中将变量声明为extern

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

    【讨论】:

      猜你喜欢
      • 2014-01-28
      • 1970-01-01
      • 1970-01-01
      • 2011-04-04
      • 1970-01-01
      • 1970-01-01
      • 2012-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多