The shared library constructor fails

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!!!

+8
gcc constructor shared-libraries ld
source share
2 answers

This text is for reference only, but I come to your office for convenience :)

I am not an expert in this field, but a quick google search gave me this . Reading only the beginning of the document, and if I get it right, the problem is this:

Statically linked your program is autonomous at runtime ... it contains the whole library and is fully loaded into memory when it starts.

Associated dynamically, when a library function is called from your program at runtime, the linker tries to resolve all unresolved function references by looking to see if there is an implementation in any library. If it loads this implementation, that is, just the function code.

So, if I am right, and the dynamic linker just loads parts of the libraries, i.e. necessary functions, not the whole library, then this explains why your constructor is not called when your library is linked dynamically.

-2
source share

Gcc constructor processing is not the same as processing an ELF constructor, but rather sits on top of it. To work, you need to link the glue code that is provided in the gcc startup files.

The easiest way to do this is to bind using gcc:

 gcc -shared -o testlib.so testlib.o 
+4
source share

All Articles