Is it possible to completely remove unused libraries, as ldd reports?

I clean up the rotten source tree, and I try to ensure that every executable file and every shared library is associated with only those libraries that they use directly.

To do this, I ldd -u- rbinary output and remove the specified libraries from the makefile.

For instance:

$ ldd -u -r ./libA.so
Unused direct dependencies:
        /usr/local/lib/libB.so
        /usr/local/lib/libC.so
        /lib/tls/libpthread.so.0
$ sed -i'' -e 's/-lB//' -e 's/-lC//' Makefile

Well, of course, it is libpthreadreally necessary (and in any case implicitly included in -pthread), but the rest of the libraries reported lddcan be safely deleted.

Are there any implications for my optimization? Is it completely safe?

+3
source share
4 answers

This is safe * unless one thing happens (which, fortunately, is under your control).

dlsym(RTLD_DEFAULT,...), (). , ( dlopen()), .

, , dlsym() ( , ldd), dlopen(), . .


* "" ", , ". .

+6

, , , , , . .

$ cat a.cc
int fa(){return 42;}
$ gcc -shared a.cc -o liba.so -ltermcap
$ cat main.cc
#include <stdio.h>
#include <stdlib.h>
#include <termcap.h>
int main() {
        tgetent(0,getenv("TERM"));
        printf("terminal is %d columns\n",tgetnum("co"));
}
$ gcc main.cc -o main # we didn't mention -ltermcap
/tmp/ccercfhS.o(.text+0x27): In function `main':
: undefined reference to `tgetent'
collect2: ld returned 1 exit status
$ # we mentioned -ltermcap by using -la
$ # if we'll remove -ltermcap from liba the project won't compile
$ gcc main.cc -o main -L. -la 
$ LD_LIBRARY_PATH=. ./main
terminal is 237 columns

, ​​ , .

, , , main.cc termcap.

+2

, , strace, .

strace -e open myprog> strace.out 2> & 1

Then check strace's output to see which libraries are actually open. This means any call to open () that does not return -1.

+1
source

For me, there seems to be an additional assumption that ldd will display all libraries that it cannot find as unused (they could be there during the build, so there are no errors here).

So no , you can’t rely on the results ldd -u!

(tested with ldd 2.27 under Ubuntu Ubuntu 18.04.2 and ldd 2.24 under Devuan ascii)

0
source

All Articles