How to add dependencies between ExternalProjects in CMake?

103 views Asked by At

I want to build a library libpng from source which requires libz which in turn I also want to build from source. I have one CMakeLists.txt file so far and the part that defines the build steps for both libraries looks like this:

if(NOT EXISTS ${CMAKE_BINARY_DIR}/build-zlib/build/libz.a)
  file(DOWNLOAD https://www.zlib.net/zlib-1.2.11.tar.gz zlib.tar.gz TLS_VERIFY ON)
  file(ARCHIVE_EXTRACT INPUT zlib.tar.gz)
  include(ExternalProject)
  ExternalProject_Add(zlib
    SOURCE_DIR ${CMAKE_BINARY_DIR}/zlib-1.2.11
    BINARY_DIR ${CMAKE_BINARY_DIR}/build-zlib/build
    INSTALL_COMMAND cmake -E echo "Skipping install"
    CMAKE_ARGS -DCMAKE_POSITION_INDEPENDENT_CODE=ON
  )
  message(STATUS "zlib will be built during 'make'")
endif()

if(NOT EXISTS ${CMAKE_BINARY_DIR}/build-png/build/libpng.a)
  include(ExternalProject)
  ExternalProject_Add(png
    GIT_REPOSITORY "https://github.com/glennrp/libpng.git"
    GIT_TAG "v1.6.37"
    BINARY_DIR ${CMAKE_BINARY_DIR}/build-png/build
    INSTALL_COMMAND cmake -E echo "Skipping install"
    CMAKE_ARGS -DCMAKE_POSITION_INDEPENDENT_CODE=ON
  )
  message(STATUS "libpng will be built during 'make'")
endif()

There are two problems: First, CMake doesn't know that libz has to be built before libpng. Second, even if libz would be built before, CMake doesn't know that libz will be placed in ${CMAKE_BINARY_DIR}/build-zlib/build. I suppose the second problem may be fixed by adding list(APPEND CMAKE_PREFIX_PATH ${CMAKE_BINARY_DIR}/build-zlib/build) (please correct me if I'm wrong) but how do I deal with the first problem? Freely I've tried to add add_dependencies(png zlib) but libz is not getting built before libpng. The error message therefore states that libz can't be found:

CMake Error at /snap/cmake/876/share/cmake-3.20/Modules/FindPackageHandleStandardArgs.cmake:230 (message):
  Could NOT find ZLIB (missing: ZLIB_LIBRARY ZLIB_INCLUDE_DIR)
0

There are 0 answers