Windows下Clion 中使用zlib找不到compress

Clion zlib 找不到 compressBound “undefined reference to `compressBound'”
clion安装完没有对zlib作任何改动
请问是否需要额外安装zlib

#include <iostream>
#include <zlib.h>
using namespace std;

int main()
{
    // region ## zlib.h ##

    char text[] = "zlib compress and uncompress test\nturingo@163.com\n2012-11-05\n";
    char de_text[1024];
    uLong textLength = strlen(text) + 1;  /* 需要把字符串的结束符'\0'也一并处理 */
    char* buffer = NULL;
    uLong bufferLength;

    /* 计算缓冲区大小,并为其分配内存 */
    bufferLength = compressBound(textLength); /* 压缩后的长度是不会超过bufferLength的 */
    if ((buffer = (char*)malloc(sizeof(char) * bufferLength)) == NULL)
    {
        printf("no enough memory!\n");
        return -1;
    }

    /* 压缩 */
    if (compress((Bytef *)buffer, &bufferLength, (Bytef *)text, textLength) != Z_OK)
    {
        printf("compress failed!\n");
        return -1;
    }

    /* 解压缩 */
    if (uncompress((Bytef *)de_text, &textLength, (Bytef *)buffer, bufferLength) != Z_OK)
    {
        printf("uncompress failed!\n");
        return -1;
    }

    /* 打印结果,并释放内存 */
    printf("%s", de_text);
    if (buffer != NULL)
    {
        free(buffer);
        buffer = NULL;
    }

    // endregion

    return 0;
}

问题已解决,需要额外编译zlib加入cmake-build文件夹中并在main.cpp文件头部加入#pragma comment(lib, "zlib.lib")(msvc可行,gcc没试过)

引用 皆我百晓生 小程序回复内容作答:
在Clion中使用zlib库,需要对CMakeLists.txt文件进行配置。您可以在项目的根目录中找到CMakeLists.txt文件,并在其中添加以下内容:

# Find the zlib library
find_package(ZLIB REQUIRED)

# Add the include directories for zlib
include_directories(${ZLIB_INCLUDE_DIRS})

# Add the executable and link against zlib
add_executable(compress_example example.cpp)
target_link_libraries(compress_example ${ZLIB_LIBRARIES})

这样通过find_package命令找到zlib库,然后使用include_directories添加zlib的头文件路径,最后使用target_link_libraries将项目与zlib库进行链接。

完成以上配置后,重新构建和运行项目,应该就可以解决找不到compressBound的问题了。

【以下回答由 GPT 生成】

你在Clion中使用zlib库时遇到的这个错误可能是因为在编译链接阶段找不到对应的zlib库。解决这个问题可以通过以下步骤:

  1. 首先,你需要确保你的系统中已经安装了zlib库。你可以在CMakeList.txt文件中添加以下代码来告诉Clion链接zlib库:
find_package(ZLIB REQUIRED)
target_link_libraries(your_project_name ZLIB::ZLIB)
  1. 如果你没有在系统中安装zlib库,你可以通过以下步骤来安装它:
  2. 在Windows上,你可以从zlib的官方网站(https://www.zlib.net/)下载zlib的预编译二进制文件(例如 *.dll)。
  3. 将下载的库文件复制到你的项目文件夹中,或者添加到系统路径中。
  4. 在CMakeList.txt文件中添加以下代码来链接zlib库: cmake target_link_libraries(your_project_name path_to_zlib_library)

  5. 如果你使用的是Clion的MinGW版本,你可能还需要在set(CMAKE_CXX_STANDARD_LIBRARIES "-static-libgcc -static-libstdc++")行之前添加以下代码来禁用MinGW的默认标准库:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -static-libgcc -static-libstdc++")

这些步骤应该可以解决"undefined reference to 'compressBound'"错误。如果你仍然遇到问题,请提供更多的错误信息和代码,以便能够更好地帮助你解决问题。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^