C zlib link 错误

C zlib link errors

我正在尝试学习 zlib 模块,但是当我编译我的代码时,它总是说 zlib 提供的所有函数名称都没有定义。这是我的代码,感谢任何帮助,谢谢。

#include <stdio.h>
#include <zlib.h>

int compressFile(char *infilename, char *outfilename){
        //Opens the needed files
        FILE * infile = fopen(infilename, "rb");
        gzFile outfile = gzopen(outfilename, "wb");
        //Checks if the files are correctly opened
        if (!infile || !outfile) return -1;

        char inbuffer[128];
        int numRead = 0;

        while ((numRead = fread(inbuffer, 1, sizeof(inbuffer), infile)) > 0){
                gzwrite(outfile, inbuffer, numRead);

        }
        fclose(infile);
        gzclose(outfile);

}

这里是错误

cc     test.c   -o test
test.c: In function ‘main’:
test.c:24:2: warning: implicit declaration of function ‘comressFile’ [-Wimplicit-function-declaration]
  comressFile("hello.txt", "hello.zip");
  ^
/tmp/cc32e8i4.o: In function `compressFile':
test.c:(.text+0x41): undefined reference to `gzopen'
test.c:(.text+0x7c): undefined reference to `gzwrite'
test.c:(.text+0xbd): undefined reference to `gzclose'
/tmp/cc32e8i4.o: In function `main':
test.c:(.text+0xd7): undefined reference to `comressFile'
collect2: error: ld returned 1 exit status
<builtin>: recipe for target 'test' failed
make: *** [test] Error 1

您需要 link 使用 zlib:

cc -lz test.c -o test

还有你的拼写错误。 "compressFile" 对比 "comressFile".

请记住,在 C 中 在使用函数之前声明函数是可选的。如果你不这样做,或者名字拼错了,这个函数在第一次使用时就隐式声明了,这可能不是你想要的。