cmake : externalproject で zlib と libpng を扱う例


目的

CMake の ExternalProject によって既存のプロジェクトへ zlib と libpng を取り込み扱えるようにする方法を紹介したい。

externalproject 例

external_zlib.cmake

cmake_minimum_required( VERSION 3.2 )

include_directories(${CMAKE_CURRENT_BINARY_DIR}/include)
link_directories(${CMAKE_CURRENT_BINARY_DIR}/lib)

include( ExternalProject )

set( zlib_source_path ${CMAKE_CURRENT_BINARY_DIR}/external/zlib/src/external_zlib/ )
set( zlib_cmake_file_path ${zlib_source_path}/CMakeLists.txt )

ExternalProject_Add( external_zlib
  PREFIX            ${CMAKE_CURRENT_BINARY_DIR}/external/zlib
  INSTALL_DIR       ${CMAKE_CURRENT_BINARY_DIR}
  # http://www.zlib.net/
  GIT_REPOSITORY    [email protected]:madler/zlib.git
  GIT_TAG           v1.2.8
  CMAKE_ARGS        -DASM686=off
                    -DAMD64=off
                    -DCMAKE_INSTALL_PREFIX=${CMAKE_CURRENT_BINARY_DIR}
                    -DCMAKE_COMPILER_IS_GNUCXX=${CMAKE_COMPILER_IS_GNUCXX}
                    -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
                    -DCMAKE_C_FLAGS=${GL_BINDING_C_FLAGS}
)

external_libpng.cmake

cmake_minimum_required( VERSION 3.2 )

include_directories(${CMAKE_CURRENT_BINARY_DIR}/include)
link_directories(${CMAKE_CURRENT_BINARY_DIR}/lib)

include( ExternalProject )

set( libpng_source_path ${CMAKE_CURRENT_BINARY_DIR}/external/libpng/src/external_libpng/ )
set( libpng_cmake_file_path ${libpng_source_path}/CMakeLists.txt )

ExternalProject_Add( external_libpng
  DEPENDS           external_zlib
  PREFIX            ${CMAKE_CURRENT_BINARY_DIR}/external/libpng
  INSTALL_DIR       ${CMAKE_CURRENT_BINARY_DIR}
  # http://www.libpng.org/pub/png/libpng.html
  GIT_REPOSITORY    git://git.code.sf.net/p/libpng/code
  GIT_TAG           v1.6.9
  CMAKE_ARGS        -DPNG_SHARED=off
                    -DPNG_STATIC=on
                    -DPNG_TESTS=on
                    -DPNG_DEBUG=off
                    -DPNGARG=off
                    -DBUILD_SHARED_LIBS=FALSE
                    -DCMAKE_INSTALL_PREFIX=${CMAKE_CURRENT_BINARY_DIR}
                    -DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
                    -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}
                    -DCMAKE_COMPILER_IS_GNUCXX=${CMAKE_COMPILER_IS_GNUCXX}
                    -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
                    -DCMAKE_C_FLAGS=${GL_BINDING_C_FLAGS}
)

既存プロジェクト my_app への依存性とリンク定義の例

include( external_zlib.cmake )
include( external_libpng.cmake )

add_executable( my_app main.cxx )

add_dependencies( my_app
  external_zlib
  external_libpng
)

target_link_libraries( my_app
  png
  zlibstatic
)

Note

  • 例の target_link_libraries では png より後ろに zlibstatic を記述する必要があり、順序を逆にするとリンクエラーとなる。

References