Search code examples
cstatic-linkingc-libraries

c -lz library link order (undefined reference to symbol "inflateInit2_")


I link the the library in CodeBlocks in this order,

-lz
-L/usr/local/lib
-L/usr/local/include
-pthread
-lswscale
-lavutil
-lavcodec
-lmp3lame
-lopus
-ltiff
-lvorbis
-ltheora
-ltheoraenc
-ltheoradec
-lvorbisenc
-ltiffxx
-llzma
-lva
-lavfilter
-lavformat
-lfreetype

still got error:

undefined reference to symbol "inflateInit2_"

I am wondering whether it is the library link order problem? Where should I put the -lz?


Solution

  • For GCC and Clang (and probably e.g. the Intel compiler too) the rule is that references from earlier on in the command line are satisfied from libraries specified later on in the command line.

    For example, if foo.c references functions from the library bar, then it's correct to compile with

    $ gcc foo.c -lbar
    

    , and incorrect to compile with

    $ gcc -lbar foo.c
    

    Therefore, your safest bet would be to put -lz last, so that it can satisfy reference from all the libraries specified earlier.

    Here's a relevant quote from the gcc(1) man page (-l option):

    It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. If bar.o refers to functions in z, those functions may not be loaded.

    However, even better might be to use e.g. pkg-config(1) with --libs to get the flags you need for a particular library. Some libraries also ship with custom scripts for this purpose (e.g., sdl(2)-config for SDL(2)).