0

tl;dr Is there a certain way to link libraries to ensure that thread_local variables are properly defined?

I have a class along the lines of

engine.h

class Engine
{
private:
  std::mt19937_64 m_engine;

public:
  Engine() = default;
  ~Engine() {}

  std::mt19937_64& get()
  {
    return m_engine;
  }
};

and another class that uses it,

threadrandom.h

#include "engine.h"

class ThreadRandom
{
private:
  static thread_local Engine m_engine;

public:
  ThreadRandom() = default;
  ~ThreadRandom() {}

  static const float Rnd()
  {
    std::uniform_real_distribution< float > _engine;
    return _uniform( engine() );
  }
};

I use make to add them into a library with

add_library(${PACKAGE} SHARED ${SOURCES})

and then I link it to some tests with

target_link_libraries(test ${PACKAGE})

Whenever I try to build this way the thread_local member comes up as undefined. The rest of the compilation works fine if remove the thread_local and keep the engine as simply static (then declaring it in the source file). The same problem occurs with GCC 10 and Clang 12 that I have been testing with. I can also declare a thread_local file in the main executable and have no problem executing it so think the problem occurs with linking the library.

Is there a certain way to link libraries to ensure that thread_local variables are properly defined?

  • There are some toolchains that fail with `thread_local`. It has nothing to do with compiler. The linker is the source of problems. – ALX23z Apr 15 '21 at 20:09
  • "The rest of the compilation works fine if remove the thread_local and keep the engine as simply static (then declaring it in the source file)." - It seems you know that aside from *declaring* static member in the class, you need to **define** it. Why do you think that `thread_local` static member doesn't require such definition? – Tsyvarev Apr 15 '21 at 21:57

0 Answers0