1

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

2 Answers2

3

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;
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Both your header and cpp define your variable example. You should declare the variable in your header as extern.

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

Lanting
  • 3,060
  • 12
  • 28