Why am I getting a gcc “undefined reference” error trying to create shared objects?

Recent versions of gcc/ld default to linking with --as-needed.

This means if you write -lexternal before the C file the library will automatically get excluded (the order matters when testing if things are “needed” like this)

You can fix this with either of:

  • gcc -L. -o program program.c -lexternal
  • gcc -L. -Wl,--no-as-needed -lexternal -o program program.c

The latter of which passes --no-as-needed to the linker, which would cause the library to still be linked, even if you didn’t call external() from it.

Note: -Wl,--no-as-needed isn’t applied globally to everything that’s linked, it’s only applied to things that follow it in the command line order. So -lexternal -Wl,--no-as-needed also wouldn’t work. This does mean that you can mix and match behaviours though, for example gcc -L. -Wl,--no-as-needed -lexternal -Wl,--as-needed -o program program.c -lmightneed would always link against external, but only link against mightneed if one or both of program.c/libexternal.so caused it to be needed.

Leave a Comment