This is the mail archive of the binutils@sourceware.org mailing list for the binutils project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Weak symbol in an executable, overridable by shared libraries at runtime


On Sat, Nov 02, 2013 at 10:44:32PM +0100, Lorenzo Pistone wrote:
> Is there a way to define a weak symbol in an executable (not a
> .so!), that can be overridden by the runtime linking process by a
> symbol found in another library?

No, not without making changes to linker operation.  Make your
executable a shared library, then have a "stub" executable that just
consists of startup files, like so.  Also note the tweak needed to
ld.so symbol resolution via LD_DYNAMIC_WEAK, and you may need to use
-Wl,-no-as-needed for some of the linking stages.

$ cat > weakexe.c <<EOF
#include <stdio.h>

int foo (void) __attribute__ ((weak));

int
foo (void)
{
  return 1;
}

int
main (void)
{
  printf ("foo: %d\n", foo ());
  return 0;
}
EOF
$ cat > weakso.c <<EOF
int
foo (void)
{
  return 2;
}
EOF
$ gcc -O2 -fpic -c weakexe.c 
$ gcc -O2 -fpic -c weakso.c 
$ gcc -shared -o weak.so weakso.o
$ gcc -shared -o weakmain.so weakexe.o weak.so
$ gcc -o weak weakmain.so weak.so
$ LD_LIBRARY_PATH=. ./weak
foo: 1
$ LD_LIBRARY_PATH=. LD_DYNAMIC_WEAK=1 ./weak
foo: 2


-- 
Alan Modra
Australia Development Lab, IBM


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]