How to link Zlib with Cmake

AKJ picture AKJ · Nov 14, 2018 · Viewed 10.2k times · Source

I am trying to link my file with the zlib libray but still get: undefined reference to `deflateInit_'.

I am currently using CLion, have downloaded the zLib file from the homepage and added it into the project. This is how my CmakeLists.txt looks like

cmake_minimum_required(VERSION 3.10) project(GzipTest)

set(CMAKE_CXX_STANDARD 11)

include_directories(ZLIB zlib-1.2.11)

add_executable(GzipTest main.cpp zlib-1.2.11/zlib.h)

And the code (Copying from the zpipe.c):

include "iostream"

include "zlib.h"

include "iostream"

define CHUNK 1639


FILE *fp;


int def(FILE *source, FILE *dest, int level){
    int ret, flush;
    unsigned have;
    z_stream strm;
    unsigned char in[CHUNK];
    unsigned char out[CHUNK];

    // Allocate Deflate state
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    strm.opaque = Z_NULL;

    ret = deflateInit(&strm, level);
    if (ret != Z_OK){
        return ret;
    }

}


int main(){
    fp = fopen("inputFile.txt", "r");
    if (fp == nullptr){
        perror("Could not open data");
        exit(EXIT_FAILURE);
    }
    def(fp, fp, 1); 
}

What could be missing? Thanks in advance

Answer

Matthieu Brucher picture Matthieu Brucher · Nov 14, 2018

You have to link against zlib.

If you used:

find_package(ZLIB)

Then you should have:

target_link_libraries(GzipTest ZLIB::ZLIB)

Also don't add the headers to your source files:

add_executable(GzipTest main.cpp)