010110110101 010110110101 - 22 days ago 8
Linux Question

How to build zlib with cmake in out-of-source mode?

zlib will not successfully compile using cmake in out-of-source mode.

What am I doing wrong?

Here's zlib working in-source:

mkdir test
cd test
mkdir contrib
mkdir build
cp /tmp/zlib-1.2.8.tar.gz contrib
cd contrib
tar xvf zlib-1.2.8.tar.gz
cd zlib-1.2.8
rm zconf.h
cmake .
make


Here's zlib failing out-of-source:

mkdir test
cd test
mkdir contrib
mkdir build
cp /tmp/zlib-1.2.8.tar.gz contrib
cd contrib
tar xvf zlib-1.2.8.tar.gz
cd zlib-1.2.8
rm zconf.h
cd ../../
echo -e cmake_minimum_required\(VERSION 2.6.4\)\\r\\n\
project\(MyTestApp\)\\r\\n\
\\r\\n\
add_subdirectory\(contrib/zlib-1.2.8\)\\r\\n\
> CMakeLists.txt
cd build
cmake ..
make


It fails with:

/home/blah/test/contrib/zlib-1.2.8/test/example.c:8:18: error: zlib.h: No such file or directory


NOTES:
What am I doing? I'm seeking to build a local copy of zlib. I do not want to involve the system zlib (My project involves cross-compiling).

I don't have zlib.h installed in /usr/include. (I uninstalled zlib-devel) When I do have zlib-devel package installed (which then gives me a system install of zlib, which I don't want), the error about zlib.h changes and is instead about not being able to find zconf.h.

The pathology is the same. The example.c file is not finding the correct header files. You can get a pretty good sense of how/why this happened from the CMakeLists.txt file that comes with zlib. The part where it builds the zlib library itself mentions ZLIB_PUBLIC_HDRS, but the part where it builds the example doesn't mention that variable. Hence: it is't looking for the headers locally. (I'm guessing here)

Answer Source

The out-of-source build of zlib is fine. What you did is: create a new root CMakeLists.txt, and then use the zlib source directory as a sub-directory. That does not work. The issue is probably the use of the CMake variable CMAKE_SOURCE_DIR instead of CMAKE_CURRENT_SOURCE_DIR. In the CMakeLists.txt file of zlib, try to replace one by the other.

EDIT:

In the CMakeLists.txt that comes with zlib, locate this line:

include_directories(${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_SOURCE_DIR})

and change it to this:

include_directories(${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_CURRENT_SOURCE_DIR})