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 work, i.e. it doesn't get called when the program linking my shared library is loaded.
If I change the function name to _init()
, it works. Apparently the usage of _init()
and _fini()
functions are not recommended now.
Any idea why __attribute__ ((constructor))
wouldn't work? This is with Linux 2.6.9, gcc
version 3.4.6
Edit:
For example, let's say the library code is this the following:
#include <stdio.h>
int smlib_count;
void __attribute__ ((constructor)) setup(void) {
smlib_count = 100;
printf("smlib_count starting at %d\n", smlib_count);
}
void smlib_count_incr() {
smlib_count++;
smlib_count++;
}
int smlib_count_get() {
return smlib_count;
}
For building the .so I do the following:
gcc -fPIC -c smlib.c
ld -shared -soname libsmlib.so.1 -o libsmlib.so.1.0 -lc smlib.o
ldconfig -v -n .
ln -sf libsmlib.so.1 libsmlib.so
Since the .so is not in one of the standard locations I update the LD_LIBRARY_PATH
and link the .so from a another program. The constructor doesn't get called. If I change it to _init()
, it works.
void __attribute__ ((constructor)) constructor() { ... }
. Note that it's aftervoid
and beforeconstructor()
.main
is entered. The most infamous example is OpenAL, which (at least at one time; I believe it was since fixed but I'm not sure) munged with ALSA library/device state in a way that prevented the application from later opening the ALSA device itself. Proper libraries should try their best to avoid having any global state, and if absolutely necessary, should use lazy initialization on the first library call, not ctors.