This is the mail archive of the
binutils@sourceware.org
mailing list for the binutils project.
Re: Weak symbol in an executable, overridable by shared libraries at runtime
- From: Alan Modra <amodra at gmail dot com>
- To: Lorenzo Pistone <blaffablaffa at gmail dot com>
- Cc: binutils at sourceware dot org
- Date: Sun, 3 Nov 2013 15:01:14 +1030
- Subject: Re: Weak symbol in an executable, overridable by shared libraries at runtime
- Authentication-results: sourceware.org; auth=none
- References: <52757240 dot 4020107 at gmail dot com>
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