Nicholas Hollander Nicholas Hollander - 1 year ago 64
C++ Question

Linker fails for std::map in header

I am trying to create a simple c++ program using code::blocks and mingw, and I am encountering a linking error of some sort. When I attempt to build the project, ld returns 1 with no additional details. I have tried searching online for information about this sort of issue, but I haven't been able to find anything.

I tried moving the definition of

example
from
test.hpp
to
test.cpp
, and that does resolve the linking issue, but it makes it so that I can't access
example
from other files that import
test.hpp
. I have also tried removing the namespace altogether, but I would like to avoid that for organizational reasons (If this is a totally inappropriate usage of namespaces I'd appreciate knowing). I am trying to make it so that eventually several parts of my program are able to access and update
example
during runtime.

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 output

=== 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)) ===

Answer Source

There should be a more comprehensive build log somewhere, where it will say that testing::example is defined multiple times.

The solution is simple: Only declare the variable in the header file, using the extern keyword:

// In header file
namespace testing{
    extern std::map<std::string,int> example;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download