What exactly does -rdynamic
(or --export-dynamic
at the linker level) do and how does it relate to symbol visibility as defined by the -fvisibility*
flags or visibility pragma
s and __attribute__
s?
For --export-dynamic
, ld(1) mentions:
... If you use "dlopen" to load a dynamic object which needs to refer back to the symbols defined by the program, rather than some other dynamic object, then you will probably need to use this option when linking the program itself. ...
I'm not sure I completely understand this. Could you please provide an example that doesn't work without -rdynamic
but does with it?
Edit:
I actually tried compiling a couple of dummy libraries (single file, multi-file, various -O levels, some inter-function calls, some hidden symbols, some visible), with and without -rdynamic
, and so far I've been getting byte-identical outputs (when keeping all other flags constant of course), which is quite puzzling.
Here is a simple example project to illustrate the use of
-rdynamic
.bar.c
main.c
Makefile
Here,
bar.c
becomes a shared librarylibbar.so
andmain.c
becomes a program thatdlopen
slibbar
and callsbar()
from that library.bar()
callsfoo()
, which is external inbar.c
and defined inmain.c
.So, without
-rdynamic
:And with
-rdynamic
:I use rdynamic to print out backtraces using the
backtrace()
/backtrace_symbols()
of Glibc.Without
-rdynamic
, you cannot get function names.To know more about the
backtrace()
read it over here.-rdynamic
exports the symbols of an executable, this mainly addresses scenarios as described in Mike Kinghan's answer, but also it helps e.g. Glibc'sbacktrace_symbols()
symbolizing the backtrace.Here is a small experiment (test program copied from here)
compile the program:
gcc main.c
and run it, the output:Now, compile with
-rdynamic
, i.e.gcc -rdynamic main.c
, and run again:As you can see, we get a proper stack trace now!
Now, if we investigate ELF's symbol table entry (
readelf --dyn-syms a.out
):without
-rdynamic
with
-rdynamic
, we have more symbols, including the executable's:I hope that helps!