Hello,
I'm learning C++ and i was trying to use the zlib, but i'm getting some errors when trying to compile my little project. Here is the code:

#include <string>
#include <stdexcept>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <zlib.h>
using namespace std;

std::string compress_string(const std::string& str,
                            int compressionlevel = Z_BEST_COMPRESSION)
{
    z_stream zs;                        // z_stream is zlib's control structure
    memset(&zs, 0, sizeof(zs));

    if (deflateInit(&zs, compressionlevel) != Z_OK)
        throw(std::runtime_error("deflateInit failed while compressing."));

    zs.next_in = (Bytef*)str.data();
    zs.avail_in = str.size();           // set the z_stream's input

    int ret;
    char outbuffer[32768];
    std::string outstring;

    // retrieve the compressed bytes blockwise
    do {
        zs.next_out = reinterpret_cast<Bytef*>(outbuffer);
        zs.avail_out = sizeof(outbuffer);

        ret = deflate(&zs, Z_FINISH);

        if (outstring.size() < zs.total_out) {
            // append the block to the output string
            outstring.append(outbuffer,
                             zs.total_out - outstring.size());
        }
    } while (ret == Z_OK);

    deflateEnd(&zs);

    if (ret != Z_STREAM_END) {          // an error occurred that was not EOF
        std::ostringstream oss;
        oss << "Exception during zlib compression: (" << ret << ") " << zs.msg;
        throw(std::runtime_error(oss.str()));
    }

    return outstring;
}

int main(int argc, char* argv[])
{
    std::string allinput;

    while (std::cin.good())     // read all input from cin
    {
        char inbuffer[32768];
        std::cin.read(inbuffer, sizeof(inbuffer));
        allinput.append(inbuffer, std::cin.gcount());
    }
        std::string cstr = compress_string( allinput );

        std::cerr << "Deflated data: "
                  << allinput.size() << " -> " << cstr.size()
                  << " (" << std::setprecision(1) << std::fixed
                  << ( (1.0 - (float)cstr.size() / (float)allinput.size()) * 100.0)
                  << "% saved).\n";

        std::cout << cstr;
}

And here is my compiling log:

ubuntu@eeepc:~$ g++ comp.cpp -o comp
/tmp/ccTx0M9f.o: In function `compress_string(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, int)':
comp.cpp:(.text+0x1e3): undefined reference to `deflateInit_'
comp.cpp:(.text+0x394): undefined reference to `deflate'
comp.cpp:(.text+0x412): undefined reference to `deflateEnd'
collect2: ld returned 1 exit status
ubuntu@eeepc:~$

Thanks,
Nathan Paulino Campos

Humm, is not #include"zlib.h" ?
Undefined references came from thinhs not defined in a class like static members nor initialized, constructors missing...

You need to link to the zlib library.

If i put #include "zlib.h" the errors are the same.

You need to link to the zlib library.

Look into the linker options.

> If i put #include "zlib.h" the errors are the same.
Include files tell the compiler HOW to call something.

Libraries (the thing you're missing) tell the linker (the stage after compiling) WHAT actually provides the implementation of the thing you wanted to call.

For a simple command line, it's something like g++ comp.cpp -o comp -lzlib You need to look up how to use the -l options, and substitute an appropriate name for the library.

commented: Danke. I was short on hints. +27

If i try to compile by the command g++ comp.cpp -o comp -lzlib i'm getting this errors:

ubuntu@eeepc:~$ g++ comp.cpp -o comp -lzlib
/usr/bin/ld: cannot find -lzlib
collect2: ld returned 1 exit status
ubuntu@eeepc:~$

Thanks,
Nathan Paulino Campos

Read the zlib install instructions to find out
a) what it is called
b) where it is stored (you might need -L option as well)

On Linux, a library called libfoo.a would be specified with -lfoo

I've read a tutorial of installing zlib, but i've already installed it correct at the first time, but if i use -Lzlib , i got the same errors if i didn't putted it.

Thanks!

-L/path/to/mylibrary

Did you read about -L before trying it

-Lsearchdir
-L searchdir
Add path searchdir to the list of paths that ld will search for archive libraries and ld control scripts. You may use this option any number of times. The directories are searched in the order in which they are specified on the command line. Directories specified on the command line are searched before the default directories. All -L options apply to all -l options, regardless of the order in which the options appear. The paths can also be specified in a link script with the SEARCH_DIR command. Directories specified this way are searched at the point in which the linker script appears in the command line.

Does what you tried look like a path?

Do you even know what the library is called (see my .a thing above)? Or are you just trying random combinations of 'z' 'l' 'i' and 'b' to see what happens.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.