1

Here are the files responsible for this linker error (Only showing file, namespace and class names):

// PubSub.hpp:
#ifndef PubSub_hpp
#define PubSub_hpp
namespace PubSub {
class Publisher {}
}
}
#endif

// Client.hpp:
#ifndef Client_hpp
#define Client_hpp
#include "PubSub.hpp"
class Client {
}
#endif

// Scene.hpp:
#ifndef Scene_hpp
#define Scene_hpp
#include "Client.hpp"
class Scene {
}
#endif

The code compiles without errors in this state. But as soon as I introduce a variable in PubSub.hpp under the namespace PubSub like below:

// PubSub.hpp:
#ifndef PubSub_hpp
#define PubSub_hpp
namespace PubSub {
class Publisher {}
}
Publisher NetworkEventPublisher("someName");
}
#endif

I get the linker error in the title. I can find a workaround but I am trying to learn C++ so I'm asking what's the rule causing this?

Élodie Petit
  • 5,774
  • 6
  • 50
  • 88

2 Answers2

2

That error happens because including this header file into more than one translation unit (.cpp/.cc file) creates an object in the translation unit with the same name (aka symbol).

If you need one instance of the class declare it in the header as extern and define in a .cc file.

If you need a copy in each translation unit, declare and define the object in the header as const, such objects are implicitly static.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
2

But as soon as I introduce a variable in PubSub.hpp

If you include a PubSub.hpp in more than one translation unit (.cpp file) then your NetworkEventPublisher will be defined more than once, and this is what linker in complaining about.

The solution is to move:

Publisher NetworkEventPublisher("someName");

to implementation file (ie. PubSub.cpp). If you want other translation unit see it, then add to PubSub.hpp extern declaration : extern Publisher NetworkEventPublisher;

marcinj
  • 48,511
  • 9
  • 79
  • 100