C++ – Linking static libraries to other static libraries

.aclinkerunix-ar

I have a small piece of code that depends on many static libraries (a_1-a_n). I'd like to package up that code in a static library and make it available to other people.

My static library, lets call it X, compiles fine.

I've created a simple sample program that uses a function from X, but when I try to link it to X, I get many errors about missing symbols from libraries a_1 – a_n.

Is there a way that I can create a new static library, Y that contains X and all the functionality needed by X (selected bits from a_1 – a_n), so that I can distribute just Y for people to link their programs to?


UPDATE:

I've looked at just dumping everything with ar and making one mega-lib, however, that ends up including a lot of symbols that are not needed (all the .o files are about 700 MB, however, a statically linked executable is 7 MB). Is there a nice way to include only what is actually needed?


This looks closely related to How to combine several C/C++ libraries into one?.

Best Answer

Static libraries do not link with other static libraries. The only way to do this is to use your librarian/archiver tool (for example ar on Linux) to create a single new static library by concatenating the multiple libraries.

Edit: In response to your update, the only way I know to select only the symbols that are required is to manually create the library from the subset of the .o files that contain them. This is difficult, time consuming and error prone. I'm not aware of any tools to help do this (not to say they don't exist), but it would make quite an interesting project to produce one.