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 … Read more

How to force gcc to link an unused static library

Use –whole-archive linker option. Libraries that come after it in the command line will not have unreferenced symbols discarded. You can resume normal linking behaviour by adding –no-whole-archive after these libraries. In your example, the command will be: g++ -o program main.o -Wl,–whole-archive /path/to/libmylib.a In general, it will be: g++ -o program main.o \ -Wl,–whole-archive … Read more

GNU gcc/ld – wrapping a call to symbol with caller and callee defined in the same object file

You have to weaken and globalize the symbol using objcopy. -W symbolname –weaken-symbol=symbolname Make symbol symbolname weak. This option may be given more than once. –globalize-symbol=symbolname Give symbol symbolname global scoping so that it is visible outside of the file in which it is defined. This option may be given more than once. This worked … Read more

How to print the ld(linker) search path

You can do this by executing the following command: ld –verbose | grep SEARCH_DIR | tr -s ‘ ;’ \\012 gcc passes a few extra -L paths to the linker, which you can list with the following command: gcc -print-search-dirs | sed ‘/^lib/b 1;d;:1;s,/[^/.][^/]*/\.\./,/,;t 1;s,:[^=]*=,:;,;s,;,; ,g’ | tr \; \\012 The answers suggesting to use … Read more

I don’t understand -Wl,-rpath -Wl,

The -Wl,xxx option for gcc passes a comma-separated list of tokens as a space-separated list of arguments to the linker. So gcc -Wl,aaa,bbb,ccc eventually becomes a linker call ld aaa bbb ccc In your case, you want to say “ld -rpath .“, so you pass this to gcc as -Wl,-rpath,. Alternatively, you can specify repeat … Read more

LD_LIBRARY_PATH vs LIBRARY_PATH

LIBRARY_PATH is used by gcc before compilation to search directories containing static and shared libraries that need to be linked to your program. LD_LIBRARY_PATH is used by your program to search directories containing shared libraries after it has been successfully compiled and linked. EDIT: As pointed below, your libraries can be static or shared. If … Read more