1

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?

Kevin Kreiser
  • 594
  • 5
  • 11

1 Answers1

2

CMake comes with the Threads package for that very purpose:

find_package(Threads REQUIRED)
target_link_libraries(header-only-project INTERFACE Threads::Threads)
  • Ah yes I am aware of that but the main thing I'm worried about is that downstream projects know that my header only library depends on `Threads::Threads`. I had assumed that `Threads::Threads` is a target that resolves differently depending on the platform where you run `find_package(Threads)`. I don't understand how to generically say hey, when you use my header only library you will need to depend on `Threads::Threads`, whatever that works out to on your system. Maybe that is exactly how it works, I had just assumed that the Threads target was platform specific. – Kevin Kreiser Jun 10 '21 at 17:41
  • Ah but maybe indeed its a non-issue because doing `add_subdirectory` of the above cmake will indeed run `find_package` and resolve the `Threads` target only then on the target platform. Hahaha sorry for taking so long for it to sink in.. Is this understanding correct? – Kevin Kreiser Jun 10 '21 at 17:45
  • Also what about `package_config_file`s? Will they work properly, passing along the thread dependency? I suppose they would too because you would have had to `make install` them on the target platform, presumably. – Kevin Kreiser Jun 10 '21 at 17:46
  • 1
    "when you use my header only library you will need to depend on Threads::Threads". That's what `target_link_libraries()` does. Any target depending on your library will "inherit" the dependency. –  Jun 10 '21 at 18:37
  • 1
    "Also what about package_config_file" as long as you `EXPORT` the target themselves and not just the headers and binaries, it should "just work". –  Jun 10 '21 at 18:41