R. Peereboom
R. Peereboom

Reputation: 213

Unresolved linker error with extern'ed global variable in multiple source files

I have an unresolved external symbol error that I can't seem to find the source off. I am trying to give global access to an Engine class by declaring an instance of Engine to have external linkage (g_engine). My main.cpp file is the only file that defines this instance (as far as I have been able to find out). And that works fine. But when I add a call to a method on g_engine in another source file I get a linker error.

engine.hpp:

#include <other_stuff>
#include "Map.hpp"

class Engine
{
public:
  std::shared_ptr<Map> map;
  void run();
  void do_stuff();
  // other methods
};

extern Engine g_engine;  // Declared in header file

main.cpp:

#include "engine.hpp"

Engine g_engine;  // Defined only here

int main()
{
  g_engine.run();
  return 0;
}

map.hpp:

// Only includes standard headers

class Map
{
  void some_func();
}

EDIT: added comment to the constructor

map.cpp:

#include "engine.hpp"

Map::Map()
{
  // Calls some_func somewhere.
}

void Map::some_func()
{
  // g_engine.do_stuff()  <--- Uncommenting this line causes a linker error.
}

EDIT: Added Engine.cpp

Engine.cpp:

Engine::Engine()
{
  map = std::make_shared<Map>();
}

void Engine::run()
{
  // unrelated code
}

With the line commented out, no error is given and the application runs fine. When the line is uncommented, compiling is fine, but a linker error is given:

Error   1   error LNK2001: unresolved external symbol "class Engine g_engine" (?g_engine@@3VEngine@1@A) map.obj.

Upvotes: 3

Views: 2745

Answers (1)

Codeguard
Codeguard

Reputation: 7965

When undecorated, ?g_engine@@3VEngine@1@A is class Engine::Engine g_engine. Are you missing a namespace somewhere?

Upvotes: 5

Related Questions