'Install a prebuilt library before building the rest of a CMake project, and link targets to the installed version

I intend to ship a directory containing a CMake project building some C++ code that depends on a prebuilt static library shipped along with the CMake project.

I would like CMake to build the project by first installing the prebuilt library to the default location (e.g. /usr/local/lib), and only then building the other targets, making them link to the installed version of the library rather than the copy in the build tree.

How can this be achieved?

Edit: I can tell from replies that this is not how it is supposed to be done.

The reason I considered this is that I first tried to link to the copy in the build tree in the build step, but then when I installed the executable, the linker could not find the library unless the execeutable was called from the same directory. I supposed I needed to install also the library to a standard location, but perhaps what I need to do is force some path variable to be absolute rather than relative, or something else I am missing? Below is a minimum CMakeLists.txt example:

include_directories("${CMAKE_SOURCE_DIR}") # source code here
link_directories("${CMAKE_SOURCE_DIR}")    # libmylib.a here

add_executable(my_target my_target.cpp)
target_link_libraries(my_target PRIVATE mylib)

install(TARGET my_target RUNTIME DESTINATION bin ARCHIVE DESTINATION lib CONFIGURATIONS Release)

After building and installing, I can run my_target from anywhere (because it was installed to /usr/local/lib), but unless I call it from CMAKE_SOURCE_DIR, it quits immediately with the following error message:

libc++abi: terminating with uncaught exception of type std::runtime_error: No such file libmylib.a
Abort trap: 6


Solution 1:[1]

If it's static, why install it (what @Stephen-Newell said) ? Use add_library(my_prebuilt_lib STATIC IMPORTED), set the IMPORTED_LOCATION for the library to the place in your build tree where it lives, and link with that.

You could still install the library if you want others also to statically link to it, but you don't need that in your own build.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adriaan de Groot