How to combine several C/C++ libraries into one?

I'm tired of adding ten link libraries into my project, or requiring eight of them to use my own. I'd like to take existing libraries like libpng.a, libz.a, libjpeg.a, and combine them into one single .a library. Is that possible? How about combining .lib libraries?


You could extract the object files from each library with

ar x <library name>

and then merge them all into a new library with

ar cs <new library name> <list each extracted object file>

On Unix like systems, the ld and ar utilities can do this. Check out http://en.wikipedia.org/wiki/Ar_(Unix) or lookup the man pages on any linux box or through google, e.g 'unix man ar'.

Please note that you might be better off linking to a shared (dynamic) library. This would add a dependency to your executable but will dramatically reduce its size, especially if you're writing a graphic application.


On Linux or MinGW or Cygwin, with GNU toolchain:

ar -M <<EOM
    CREATE libab.a
    ADDLIB liba.a
    ADDLIB libb.a
    SAVE
    END
EOM
ranlib libab.a

Or if you can keep the existence of liba.a and libb.a:

ar crsT libab.a liba.a libb.a

On Windows, with MSVC toolchain:

lib.exe /OUT:libab.lib liba.lib libb.lib