Search code examples
cgccstatic-linkingmsys2bzip2

How can I link the 3rd party library bzip2 in my gcc compiler?


I'm a python developer new to C and developing C code on Windows that needs to work on Windows and Linux.

To that end, I downloaded MSYS2 and used pacman to install gcc and bz2.

My question is: How do I use bzip2 in my C code.

When I try to compile this C code:

#include <bzlib.h>

using the command gcc test.c -lbzip2 -o test.out I get the following error:

test.c:1:10: fatal error: bzlib.h: No such file or directory

Am I including the correct header file? Am I linking it correctly?

When not using 3rd party libraries a simple "hello world" program compiles and executes fine.


Solution

  • Short version: assuming you are using the MSYS target, pacman -S libbz2-devel.


    Long version: In MSYS2 you can find which package contains a file using:

    pacman -F bzlib.h
    

    to which the answer is:

    mingw32/mingw-w64-i686-bzip2 1.0.8-1 [installed]
        mingw32/include/bzlib.h
    mingw64/mingw-w64-x86_64-bzip2 1.0.8-1 [installed]
        mingw64/include/bzlib.h
    msys/libbz2-devel 1.0.8-1 (development)
        usr/include/bzlib.h
    

    To interpret this output, first understand that an MSYS2 installation supports three different development targets:

    • mingw32 (builds native Win32 applications using mingw-w64)
    • mingw64 (builds native Win64 applications using mingw-w64)
    • msys (builds Win32 or Win64 applications that depend on MSYS DLLs and runtime environment, using a custom GCC port and runtime library, and supports a lot of POSIX functionality).

    When you install MSYS2 you will get three startup scripts in the Start Menu , one for each of those environments.

    The output of pacman -F above told us that for targets mingw32 and mingw64, the package bzip2 contains the files required to do development with bzip. However, on the msys target, the package libbz2-devel is required.

    This is a common package layout in msys and in the various *nix package managers (MSYS2 pacman is a port of ArchLinux pacman):

    • bzip2 is the binaries for using bzip2 in your shell
    • libbz2 is a shared object binary (DLL)
    • libbz2-devel is the header files and static libraries that you need to link bzip2 into your program.

    You can list the files for each package with pacman -F --list libbz2-devel etc.

    The mingw32/mingw64 targets typically have single packages that include all of those three things in the one package, e.g. pacman -F --list mingw64/mingw-w64-x86_64-bzip2.

    I assume you are using msys target as otherwise this question would not have arisen .