tags:

views:

991

answers:

2

Suppose I have a number of C static libraries say libColor.a which depends on libRGB.a which in turn depends on libPixel.a . The library libColor.a is said to depend on library libRGB.a since there are some references in libColor.a to some of symbols defined in libRGB.a. How do I combine all the above libraries to a new libNewColor.a which is independent?

Independent means the new library should have all symbols defined. So while linking I just need to give -lNewColor. The size of the new library should be minimal i.e it should not contain any symbols in libRGB.a which is not used by libColor.a etc. I tried my luck using various options in ar command (used to create and update static libraries/archives).

+4  A: 

A static library is not much more than an archive of some object files (.o). What you can do is extract all the objects in the two libraries (using "ar x") and then use "ar" to link them together in a new library.

Mark Probst
+4  A: 

1/ Extract ALL of the object files from each library (using ar) and try to compile your code without the libraries or any of the object files. You'll get an absolute bucket-load of undefined symbols. If you get no undefined symbols, go to step 5.

2/ Grab the first one and find out which object file satisfies that symbol (using nm).

3/ Write down that object file then compile your code, including the new object file. You'll get a new list of undefined symbols or, if there's none, go to step 5.

4/ Go to step 2.

5/ Combine all the object files in your list into a single library (again with ar).

Bang! There you have it. Try to link your code without any of the objects but with the new library.

This whole thing could be relatively easily automated with a shell script.

paxdiablo
Unnecessarily complicated, you could just extract all the .o files into a big .a, as when it's finally linked into an executable, the linker will discard any unused ones anyway
MarkR
@MarkR, @AIB wanted the size of the *library* to be minimal, not the size of the executable.
paxdiablo
Accepting it,though I would love a oneliner which does that. Like passing some options to ld to link with only the symbols needed etc...
AIB
@CID, the functionality is not thought necessary. When you link with a static library, it doesn't pull in everything from the library to make the executable. It brings in only the object files within the library to satisfy the undefined symbols.
paxdiablo
Hence the size of the *executable* is minimized to only what it needs. The link editor (ld) *will* only bring in the symbols needed. Your original question was about minimizing library size - if you really meant executable size, that's already being done for you.
paxdiablo
@PaxI meant library size only.. I was looking for some ar options similar to what a linker does for minimizing the executable size. I want a very thin combined library...with all non essentials stripped off.
AIB