In my shared library I have to do certain initialization at the load time. If I define the function with the GCC attribute __attribute__ ((constructor))
it doesn\'t
Okay, so I've taken a look at this, and it looks like what's happening is that your intermediate gcc
step (using -c
) is causing the issue. Here's my interpretation of what I'm seeing.
When you compile as a .o
with setup()
, gcc
just treats it as a normal function (since you're not compiling as a .so
, so it doesn't care). Then, ld
doesn't see any _init()
or anything like a DT_INIT
in the ELF's dynamic section, and assumes there's no constructors.
When you compile as a .o
with _init()
, gcc
also treats it as a normal function. In fact, it looks to me like the object files are identical except for the names of the functions themselves! So once again, ld
looks at the .o
file, but this time sees a _init()
function, which it knows it's looking for, and decides it's a constructor, and correspondingly creates a DT_INIT
entry in the new .so
.
Finally, if you do the compilation and linking in one step, like this:
gcc -Wall -shared -fPIC -o libsmlib.so smlib.c
Then what happens is that gcc
sees and understands the __attribute__ ((constructor))
in the context of creating a shared object, and creates a DT_INIT
entry accordingly.
Short version: use gcc
to compile and link in one step. You can use -Wl
(see the man page) for passing in extra options like -soname
if required, like -Wl,-soname,libsmlib.so.1
.
From this link :
"Shared libraries must not be compiled with the gcc arguments -nostartfiles'' or-nostdlib''. If those arguments are used, the constructor/destructor routines will not be executed (unless special measures are taken)."
gcc/ld doesn't set the DT_INIT bit in the elf header when -nostdlib is used . You can check objdump -p and look for the section INIT in both cases. In attribute ((constructor)) case you wont find that INIT section . But for __init case you will find INIT section in the shared library.