How to Install zlib on Ubuntu 22.04 or 20.04
If a build or a program throws an error about missing zlib.h or the gzopen function, you’re probably missing the development headers for zlib. The runtime library is usually pre‑installed, but the dev package isn’t always there. Below are the quick steps to get everything working on either Ubuntu 22.04 or 20.04.
1. Check if zlib is already in your system
dpkg -l | grep libz
If you see libz1 or libz2, the runtime part is fine. If you also have libz-dev, you’re good to go and can skip the rest.
2. Install the runtime library (if it’s missing)
sudo apt update && sudo apt install zlib1g
This pulls in the shared libraries your programs need at run time. It’s tiny, so even if you already have it, running this command is safe.
3. Install the development headers
sudo apt install libz-dev
Why does this matter? Most compilation errors mention “cannot find zlib.h” or “undefined reference to gzopen.” Those messages mean your compiler can’t locate the header file, and at link time it can’t find the library. libz-dev provides /usr/include/zlib.h and the static library needed for linking.
4. Verify the installation
gcc -lz -o test_zlib test.c 2>/dev/null && echo "Link succeeded"
If you get “Link succeeded” with no errors, you’re all set. If not, double‑check that libz-dev is installed.
5. A real‑world scenario I’ve seen
Last month, a friend was compiling an old OpenSSL fork on Ubuntu 20.04 and hit:
fatal error: zlib.h: No such file or directory
He thought it was a broken source tree until I told him to run sudo apt install libz-dev. The build went from 10 minutes of frustration to 2 seconds of success.
6. Optional: Install a specific version or use Snap
If you need an older version for legacy software, you can grab it from the Ubuntu package archive:
apt-get download zlib1g=1.2.11-0ubuntu2.3
Or use Snap if your project prefers containerized libraries:
sudo snap install core20
But for most developers, the APT route is simpler.
That’s all there is to it. Install, compile, and get back to hacking.