c++static-librarieslinker-errorszliblibzip

Undefined reference to static library methods inside another static library


After failing to install a C++ libzip wrapper named libzippp because of a broken Cmake, I decided to compile/link it myself as it's tiny enough.

Problem is that this lib has two dependencies, zlib and libzip. So I Cmaked those two and proceeded into making the .a using MinGW (win32). I then linked my library to my program and then compiled it, no errors.

Code below:

//lib creation command lines  

    g++ -c libzippp.cpp -o libzippp.o -std=c++11 -lzlib -lzip
    ar rcs libzippp.a libzippp.o

//Programm compilation (simplified)

    $(CC) -o $(EXEC) $(OBJ) $(CLFLAG) -lzip -lzlib -lzippp

After that I tried executing basic libzippp methods but here began the errors as the linker calls out for undefined reference.

The undefined reference comes from inside the lib, they're undefined references to the "Libzip" dependency

c:/mingw/bin/../lib/gcc/mingw32/5.3.0/.././..
  /libzippp.a(libzippp.o):libzippp.cpp:(.text+0x236e): 
                                        undefined reference to `_imp__zip_fclose'

But if I simply compile my program using libzippp as a simple compile unit I'm able to use the lib without any linker errors.

Example below :

//Compilation works, lib works

    $(CC) -o $(EXEC) $(OBJ) libzippp.h libzippp.cpp $(CLFLAG) -lzip -lzlib

As a I'm not a very experienced programmer I've assumed that I just failed the creation of the lib. It's the first time I've make a lib that needs other libs to work and I believe my error come from here.


Solution

  • You need to move -lzippp before -lzip, otherwise linker will not link files from libzip:

    $(CC) -o $(EXEC) $(OBJ) $(CLFLAG) -lzippp -lzip -lzlib
    

    That's how static libs work.