I have the following problem. I am writing a shared library
#include <stdio.h> #include <stdlib.h> static void __attribute__ ((constructor)) test_init(void); static void __attribute__ ((destructor)) test_clean(void); /* Initialization */ static void test_init(void){ fprintf(stderr,"initialized\n"); fflush(stderr); } /* CleanUp */ static void test_clean(void){ fprintf(stderr,"cleaned up\n"); fflush(stderr); } double test (double x){ return 2.0*x; }
And compile it with
gcc -c -fPIC testlib.c -o testlib.o
ld -shared -o libtest.so testlib.o
Then I include it in the test program
#include <stdio.h> #include <stdlib.h> extern double test(double x); void main(void){ printf("%.10e\n",test(10.0)); }
which I compile and start using
gcc testprog.c -o testprog -L. -ltest
LD_LIBRARY_PATH = .. / testprog
Then the output is set
2.0000000000e + 01
which means the constructor / destructor is not executing. On the other hand, if I compile
ar rvs testlib.a testlib.o
gcc testprog.c testlib.a -o testprog
program output is set
testprog initialized 2.0000000000e + 01 cleared
Why are constructors not executed if the library is linked dynamically?
I am using the following versions
GNU ld (GNU Binutils; openSUSE 11.3) 2.20.0.20100122-6 gcc version 4.5.0 20100604 [version gcc-4_5-branch 160292] (SUSE Linux)
Thank you in advance for your help!
Edited: 2011-04-13, 11:05
Thank you very much luxifer,
the document helped indirectly! The magic hint was to use the linker through the compiler ...
gcc -fPIC testlib.c -shared -Wl, -soname, libtest.so -o libtest.so
working!!!