I'm trying to build a library (with a xerces dependency) with cmake that will be run in a container that does not have Xerces installed.
add_library(MyLib STATIC <files...>)
I can find similar questions with answers. For example:
- https://discourse.cmake.org/t/how-to-statically-link-external-library-by-target-link-libraries/1718/2
- How do I tell cmake I want my project to link libraries statically?
- How do I tell CMake to link in a static library in the source directory?
and the answers indicate that I CAN do something like:
add_library(xercesc STATIC IMPORTED)
set_target_properties(xercesc PROPERTIES IMPORTED_LOCATION /usr/lib/x86_64-linux-gnu/libxerces-c.a)
set_target_properties(xercesc PROPERTIES INTERFACE_INCLUDE_DIRECTORIES /usr/include)
target_link_libraries(MyLib xercesc)
or maybe just
target_link_libraries(MyLib /usr/lib/x86_64-linux-gnu/libxerces-c.a)
but there's always a reply somewhere that you SHOULDN'T really do it that way, and that the RIGHT way looks more like:
find_package(XercesC 3.2.0 REQUIRED)
target_link_libraries(MyLib PRIVATE XercesC::XercesC)
however that results in an ImportError: libxerces-c-3.2.so: cannot open shared object file: No such file or directory
once I try to run in a container without xerces installed.
I think a main part of why the first two methods are discouraged is the hardcoding of the path. find_package(XercesC 3.2.0 REQUIRED)
exposes two variables pointing to the .so
but none pointing to the .a
or folder where they both reside. There's a CMAKE_FIND_LIBRARY_SUFFIXES variable that I could use if find_library
worked, but no such thing that applies to find_package
.
So ultimately my question is what is the right or idiomatic way to statically import an external library (xerces in this case) with cmake?