Set linker search path for build in CMake

Viewed 16552

It seems this question has been asked very often before but none of the solutions seem to apply in my case.

I'm in a CMake/Linux environment and have to run an executable binary during the build step (protoc in particular).

This binary needs a library but it's not installed (and cannot be) in the in the standard directories like /usr, so the library cannot be found.

Unfortunately I cannot manipulate the protoc call because it's embedded in a 3rd party script.

I can now set LD_LIBRARY_PATH before every make or set it system wide but this is very inconvenient especially when it comes to IDEs in which the build takes place or distributed build scenarios with continuous build environments.

I tried to set LD_LIBRARY_PATH via

set(ENV{LD_LIBRARY_PATH} "/path/to/library/dir")

but this seems to have no effect during the build step.

So my question is: can I set a library search path in CMake which is used during the build?

3 Answers

I had a similar issue for an executable provided by a third party library. The binary was linked against a library not provided by the distribution but the required library was included in the libs directory of the third party library.

So running LD_LIBRARY_PATH=/path/to/thirdparty/lib /path/to/thirdparty/bin/executable worked. But the package config script didn't set up the executable to search /path/to/thirdparty/lib for the runtime dependent so CMake would complain when CMake tried to run the executable.

I got around this by configuring a bootstrap script and replacing the IMPORTED_LOCATION property with the configured bootstrapping script.

_thirdpartyExe.in
#!/bin/bash
LD_LIBRARY_PATH=@_thirdpartyLibs@ @_thirdpartyExe_LOCATION@ "$@"
CMakeLists.txt
find_package(ThirdPartyLib)
get_target_property(_component ThirdPartyLib::component LOCATION)
get_filename_component(_thirdpartyLibs ${_component} DIRECTORY)
get_target_property(_thirdpartyExe_LOCATION ThirdPartyLib::exe IMPORTED_LOCATION)
configure_file(
  ${CMAKE_CURRENT_LIST_DIR} _thirdpartyExe.in
  ${CMAKE_BINARY_DIR}/thirdpartyExeWrapper @ONLY
)
set_target_properties(ThirdPartyLib::exe PROPERTIES IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/thirdpartyExeWrapper)

Honestly I view this as a hack and temporary stop gap until I fix the third party library itself. But as far as I've tried this seems to work on all the IDE's I've thrown at it, Eclipse, VSCode, Ninja, QtCreator, ... etc

Related