AKJ
AKJ

Reputation: 1048

How to link Zlib with Cmake

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

Upvotes: 19

Views: 40799

Answers (2)

AKJ
AKJ

Reputation: 1048

It seems this old post is getting a lot of traction. The solutions to linking zlib with CMake are either:

  1. To download zlib, if on Linux with

     sudo apt-get install zlib1g-dev
    

    and then following what Matthieu proprosed.

  2. Or download zlib like in 1 and do:

     add_executable(my_executable main.cpp)
     target_link_libraries(my_executable z)
    
  3. Or just download zlib from their homepage: https://zlib.net/, then save it in a 'deps' folder. Modify the CMakeList in the zlib folder with

     set(ZLIB_DEPS_DIR ${CMAKE_CURRENT_BINARY_DIR} PARENT_SCOPE)
    

    and in the main CMakeList, do

     add_executable(my_executable main.cpp)
     add_subdirectory(deps)
     include_directories(my_executable ${ZLIB_DEPS_DIR})
     target_link_libraries(my_executable zlib)
    

Upvotes: 8

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

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)

Upvotes: 28

Related Questions