How to link an imported shared library to an executable without hard-coding the path and file name?


My CMake project uses some third party libraries which I declared as IMPORTED then I set the IMPORTED_IMPLIB or IMPORTED_LOCATION properties (depending on compiler and type of library) to the full path and file name. I declared the libraries IMPORTED because the libraries’ own build system consists of a complex mix of Python, CMake and macros which I found difficult to integrate into my own project. Here are key lines of code extracted from my script.

add_executable(aten_libtorch aten_min.cpp)
add_library(torch SHARED IMPORTED)
# The next line hard-codes the library path and file name in the executable
set_target_properties(torch PROPERTIES IMPORTED_LOCATION ${ATEN_LIB_DIR}/shared/
target_link_libraries(aten_libtorch torch c10)

Is the code above standard practice for imported libraries?
The disadvantage is that when I move the library, for example on Linux, to another location, I then have to amend the script. Instead, I wanted to provide the plain library name, such as torch_cpu and a list of relative directories to search. Is this possible?

Why not use the C++ distribution of PyTorch directly? See for an example.

A generic way I handle this kind of situation is to use find_library with platform-specific PATHS and PATH_SUFFIXES.

For the toughest cases where I can’t use find_library, I use foreach and if(EXISTS) and build filenames with CMAKE_STATIC_LIBRARY_SUFFIX and similar.

because I find building libraries with debug symbols is a useful way to learn them. In addition, I want to learn CMake.

In my opinion this is a useful technique to know. I run into projects where their own pkg-config .pc and Cmake scripts are not completely correct on all platforms so I use this technique for workaround

I was hoping to write one single CMake script which could build my project on all supported compilers / platforms / built types without having to code any specific compiler / platform / built type logic with if(MSVC) .. or if(UNIX).. etc. Is this an unrealistic expectation?

Yes that’s how I do it. If() statement feeding above techniques