Link error building libpng and zlib with CMAKE, FetchContent and Visual Studio 2019 in Windows 10 x64

Viewed 799

I'm trying to build libpng with CMAKE, but it requires zlib, so I'm trying to build them both but not having any luck. I like FetchContent so I can specify a GIT_TAG and easily update that in the future if needed. For now I have just a blank test.c file to illustrate the problem.

I get these link errors:

LNK1120 1 unresolved externals 
MinimalApp\out\build\x64-Debug\_deps\libpng-build\png-fix-itxt.exe

LNK2019 unresolved external symbol crc32 referenced in function main

When I build with this CMakeLists.txt

cmake_minimum_required (VERSION 3.14)

include(FetchContent)

project(MinimalApp)

FetchContent_Declare(
    zlib
    GIT_REPOSITORY https://github.com/madler/zlib.git
    GIT_TAG        v1.2.11
)

FetchContent_MakeAvailable(zlib)

set(ZLIB_INCLUDE_DIR ${zlib_SOURCE_DIR} ${zlib_BINARY_DIR})
set(PNG_BUILD_ZLIB ON CACHE BOOL "Custom zlib Location, else find_package is used")

FetchContent_Declare(
    libpng
    GIT_REPOSITORY  https://github.com/glennrp/libpng.git
    GIT_TAG        v1.6.37
)
FetchContent_MakeAvailable(libpng)

include_directories(
    ${libpng_SOURCE_DIR}
    ${libpng_BINARY_DIR}
)

add_library(MinimalApp SHARED 
    "test.c"
)

set_target_properties(MinimalApp PROPERTIES
    LIBRARY_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/../bin/${CMAKE_BUILD_TYPE}/x64
    RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/../bin/${CMAKE_BUILD_TYPE}/x64
) 

My test.c file is blank.

1 Answers

I ran into this problem recently and I believe you also need to set the ZLIB_LIBRARY cmake variable. libpng expects this variable to be set if you are using PNG_BUILD_ZLIB.

This can be as simple as:

set(ZLIB_LIBRARY zlib)
Related