Search code examples
c++cmakecross-platform

How do you specify a threads dependency in cmake for distributing a header-only library in a cross-platform way?


I was contributing to a nice little c++ header-only library and I was fixing up the cmake to make the library properly installable and findable/usable by other projects. The library itself does make use of various parts of the stl including those that you are required to link manually. Specifically it makes use of std::thread et al. How does one, in a cross-platform way, specify that a header-only library depends on linking pthread on linux but do something else on windows or other platforms?

Maybe this is a non-issue but I had assumed that you should do something like this for linux:

target_link_options(header-only-project INTERFACE -pthread)

However that would feel out of place on windows (where I guess you get threads without extra linker flags?). What's the right way to go about specifying dependencies like this in a cross platform way when distributing a library that isn't already in binary form?


Solution

  • CMake comes with the Threads package for that very purpose:

    find_package(Threads REQUIRED)
    target_link_libraries(header-only-project INTERFACE Threads::Threads)