Search code examples
gcclinkerldldd

Using `--as-needed` but `ldd -u -r` still reports unused direct dependencies


For one of my binaries CMake produces cmdline that looks like this:

/opt/rh/devtoolset-8/root/usr/bin/g++  
-O3 -DNDEBUG   
-s 
-Wl,--as-needed 
-Wl,--gc-sections 
<blah-blah>.o
...
-o procmon.e 
-Wl,-rpath,/usr/local/lib64
<my lib>.a
...
/usr/local/lib64/libxalan-c.so 
/usr/local/lib64/libxerces-c.so
/home/user/vcpkg/installed/x64-linux/lib/libcurl.a 
...
-lcrypt 
<more vcpkg static libs>
-lrt 
-lpthread 
<more vcpkg static libs>
-lm 
<more vcpkg static libs>
-ldl 
<more vcpkg static libs>
-pthread 
<more vcpkg static libs>

As you see --as-needed is specified and yet I still end up with unused dependencies:

$ ldd -u -r procmon.e
Unused direct dependencies:
        /usr/local/lib64/libxalan-c.so.111
        /lib64/libcrypt.so.1
        /lib64/libm.so.6

Why?


Solution

  • --as-needed works during linking stage by ignoring a shared library (currently being processed) if it didn't resolve any currently unknown symbols. Garbage collection of sections (--gc-sections) kicks in after this and it can result in removal of all symbols references that were (on previous step) resolved with given shared lib, causing behavior mentioned in original post.

    Here is some additional reading.