在windows mingw下使用zlib

我似乎无法让zlib在windows下对mingw进行任何操作。

我下载了zlib @ http://sourceforge.net/projects/mingw/files_beta/MinGW/zlib/zlib-1.2.3-1-mingw32/ ,并将头文件和lib文件放在正确的位置。

简单的代码如:

#include <stdlib.h> #include <stdio.h> #include "zlib.h" int main(int argc, char *argv[]) { long a; char buffer[1024]; a = 1024; compress(buffer,&a,"testing",7); return 0; } 

编译:

 gcc test.c -lzlib -Wall -o test.exe 

编译好。 但是exe文件在压缩函数中崩溃。 有任何想法吗?

看看zlib手册,它说:

 ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)); 

将源缓冲区压缩到目标缓冲区。 sourceLen是源缓冲区的字节长度。 输入时,destLen是目标缓冲区的总大小,它必须至少是compressBound(sourceLen)返回的值。 退出时,destLen是压缩缓冲区的实际大小。

也许a=1024不够大? 我想你需要调用compressBound来获得合适的值。

我尝试使用MSYS的zlib(通过mingw-get访问),并得到了如下所述的相同的问题。

解决方案是做一个静态链接,而不是使用共享库。 只需删除或重命名导入库libz.dll.a,以避免链接器与msys-z.dll链接。

重新编译,它将工作。

另一种方法是从zlib.net网站自己安装zlib。 从mingw-get中删除一个。

在你的代码中使用zlib是非常简单的,文档(或者我发现的stackoverflow上的各种答案)并不明显。

以下技术适用于任何编译器和IDE。 我使用code:blocks在windows mingw中测试了它,这就是为什么我将它作为这个问题的答案发布的原因。

  1. http://www.zlib.net/下载zlib源代&#x7801;

  2. 将所有.c和.h文件从zlib源的根文件夹复制到编译器搜索路径中的文件夹。

  3. 将zlib源文件添加到IDE项目。

  4. 将#include“zlib.h”添加到您的源代码中

  5. 调用压缩或解压缩

而已。 这简直不能简单。

所有你必须要小心的是内存管理,因为这是C代码。

为了让自己的事情变得更简单,我已经组装了一个欢迎使用的c ++包装器,如下所示:

 /** ZLIB C++ wrapper Usage: <pre> #include "cZLIB.h" { // compress data in bigbuffer raven::set::cZLIB ZLIB; ZLIB.Compress( bigbuffer, sizebigbuffer ); // use compressed buffer, before ZLIB goes out of scope use( ZLIB.Buffer(), ZLIB.Length() ); } ... { // decompress data in smallbuffer raven::set::cZLIB ZLIB; ZLIB.Inflate( smallbuffer, sizesmallbuffer ) // use decompressed data, before ZLIB goes out of scope use( ZLIB.Buffer(), ZLIB.Length() ); } </pre> Build: Download this code ( cZLIB.h and cZLIB.cpp ) from https://github.com/JamesBremner/raven-set and install somewhere in your compiler search path. Let's assume you install it in folder .../src. Download the zlib source code from http://www.zlib.net/ Copy all the .c and .h files from the root folder of the zlib source to a new folder .../src/zlib Add the files cZLIB.h, cZLIB.cpp and all the files in .../src/zlib to the IDE project. Build. */ class cZLIB ... 

我建议使用MSYS2这种事情。 这些说明假定您想要编译一个64位程序,但是它们可以很容易地修改为32位。

安装MSYS2后,在开始菜单中运行“MinGW-w64 Win64 Shell”快捷方式。 通过运行安装64位工具链:

 pacman -S mingw-w64-x86_64-toolchain mingw-w64-x86_64-zlib 

然后通过运行这样的东西来编译你的代码:

 gcc test.c -lz -o test 

我没有仔细检查你的代码,但是我能够在没有任何崩溃的情况下运行你的代码,所以你的代码可能是OK的。 你的代码也没有输出,所以很难判断它是否真的有效。