0

I would like to remove dead code from a static library by specifying an entry point.

For instance:

lib1.c

int foo() { return 0; }
int bar() { return 0; }

lib2.c

#include "lib1.h"
int entry() {
    return foo();
}

new.a (lib1.a + lib2.a)

libtool -static -o new.a lib1.a lib2.a

I would like new.a to not contain int bar() because it is unused in the entry point of lib1.a, and I don't plan on using lib2.a directly.

Is this possible?

ldiqual
  • 14,493
  • 6
  • 47
  • 87
  • 1
    A static library is really nothing more than an archive of object files (the `.a` stands for "archive"). What your `libtool` command is doing is extracting the object files from the archives `lib1.a` and `lib2.a` and copy them to the new archive `new.a`. The `libtool` script and the commands it runs doesn't really examine (or have the possibility to examine) or modify the contents of the object files themselves. To remove unused code you have to do it when linking, and [this old question](https://stackoverflow.com/questions/6687630/how-to-remove-unused-c-c-symbols-with-gcc-and-ld) shows how. – Some programmer dude Sep 12 '19 at 07:09
  • `libtool` does not examine the content of the library to identify unused functions, since it works by the premise that `new.a` should export the same functions as `lib1.a` and `lib2.a`. You'll needed to manually remove the offending function(s) from `lib1.c`, rebuild `lib1.a` then recreate `new.a`. – Peter Sep 12 '19 at 10:18

1 Answers1

0

If you compile with -ffunction-sections (and possibly -fdata-sections) and link with -Wl,--gc-sections, the unreferenced functions will be removed. This is subtly different from them not being present to begin with (for example, if bar contained references to other functions or data, it could cause the files containing them to be pulled in for consideration, possibly resulting in new global ctors or overriding weak definitions) but close enough for most purposes.

The right way, on the other hand, is not to define functions that can be used independently in the same translation unit (source file). Split them into separate files and this just works automatically with no special options.

R.. GitHub STOP HELPING ICE
  • 195,354
  • 31
  • 331
  • 669
  • Wouldn't it require compiling a binary that links against those libraries? My assumption was that you can't use the linker to generate another static library. – ldiqual Sep 12 '19 at 16:49
  • @ldiqual: Indeed, it wouldn't remove the unneeded function from the library, only from programs linked to it. If you really need it out of the library, follow the right solution and separate the files. You can then do (i.e. automate) link traces for each undefined symbol in `lib2.a` to determine exactly which `.o` files from `lib1.a` you want, and extract only those `.o` files from `lib1.a` rather than copying the whole thing. – R.. GitHub STOP HELPING ICE Sep 12 '19 at 16:57