Issue
I'm on cmake version 3.12.1 and want to build a static executable that uses ZLIB. I have both the static (libz.a) and shared (libz.so) libraries on my machine. How can I tell find_package(ZLIB)
to return the static version? Maybe there's another way to find libz.a
as well?
My present workaround is to specify:
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static")
Then:
target_link_libraries (my_binary z lib1 lib2)
Critique on this approach is also welcome!
Solution
Your approach is valid given the limitations of the CMake module called by find_package(ZLIB)
, specifically FindZLIB.cmake
. While other FindXXX.cmake
modules have a special option for grabbing static libraries, the zlib module does not.
There are already a few questions on SO about this topic, but some are older than others, so there are a few options.
You can instead apply the -static
flag on a more granular level (rather than editing the global CMAKE_EXE_LINKER_FLAGS
variable) by adding it to your target_link_libraries
call. This way it will apply only to that target -- useful if you are building other non-static targets.
You could also tell CMake to search for static libraries explicitly by setting CMAKE_FIND_LIBRARY_SUFFIXES
. When find_package
is called, CMake can search for libraries ending in .a
using this:
SET(CMAKE_FIND_LIBRARY_SUFFIXES ".a")
find_package(ZLIB REQUIRED)
Answered By - squareskittles