Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to link Zlib with Cmake

Tags:

c

gzip

zlib

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

like image 369
AKJ Avatar asked Nov 14 '18 10:11

AKJ


People also ask

What is CMakeLists txt?

CMakeLists. txt file contains a set of directives and instructions describing the project's source files and targets (executable, library, or both). When you create a new project, CLion generates CMakeLists. txt file automatically and places it in the project root directory.


2 Answers

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)
like image 144
Matthieu Brucher Avatar answered Oct 03 '22 04:10

Matthieu Brucher


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})
     target_link_libraries(my_executable zlib)
    
like image 23
AKJ Avatar answered Oct 03 '22 03:10

AKJ