The new `--as-needed` option to the GNU linker
Originally published January 2012. Updated November 2023 to add how to determine the default on your system. Note: The _new_ in the title was _new_ then (in January 2012)
Recently I upgraded one of my machines to a version of the GNU linker
which by default uses the “–as-needed” option. (You can find out the
options applied on your system when you compile a program with:
gcc -Q -v
options when compiling).
This option allows the linker to ignore, i.e., not link against, some
of the libraries supplied on its command line if they are not actually
used by the shared library that is being created. For example, if you
supply the -lm
option on the command line to the linker but do not
actually use any maths functions then the ‘‘libm.so’’ library will
not be linked against.
I think it is an excellent idea to introduce this option as it will eventually force developers to think more carefully about their library dependencies. The introduction of this option as a default can, however, break quite a few builds.
The best course of action is of course to fix the inherent flaws in the builds that this option is exposing. I’ve found that two additional linker options can help immensely with this:
-
--no-undefined
, which checks that the shared library being compiled will not end up with symbols that are not resolved by any by its dependencies -
--no-allow-shlib-undefined
, which checks that none of the depend shared libraries supplied to the linker have themselves unresolved symbols
To use these options from the gcc command line remember to use the
-Wl,
prefix. So for example, use -Wl,--no-allow-shlib-undefined
Here are some link with useful information: