This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Tricky question about '_init' function of a shared lib


In article <7vqc7u$hph$1@nnrp1.deja.com>, wsonguci@my-deja.com wrote:
>Hi, folks
>
>I'm using gcc/g++ in Redhat6.0 to build a
>shared library. I need to do some initialization
>and cleaning up when the shared library is loaded
>and unloaded.
>
>So I put the intitialization code into the
>_init function, because this function will be
>called when the shared library is loaded.
>
>// sharelib.cpp
>
>// Global object
>MyClass mclass;
>
>#ifdef __cplusplus
>extern "C" {
>#endif
>
>void _init(void)
>{
>	printf("I'm _init!\n");
>	....
>}
>
>void _fini(void)
>{
>	printf("I'm _fini!\n");
>	....
>}
>
>#ifdef __cplusplus
>}
>#endif
>
>Since there is a default _init and _fini fuction in
>the standard library, when linking, I have to specify
>'-nostdlib' switch together with '-fpic -shared', and
>then link with '-lgcc'.
>
>But the problem is that, when I load the shared library,
>_init did get called, but the global C++ object was not
>initialized, I mean, 'MyClass mclass', the constructor
>of mclass was not executed. If I remove '-nostdlib' switch,
>the constructor of mclass can be executed, however, I
>have no way to link my own '_init' function which conflicts
>with the system default '_init' function. (BTW, if I specify
>static void _init(void), it'll never be executed!)
>
>This looks like a chicken-egg problem. Can any gcc/g++ guru
>help me out?


You can give the constructor - destructor attributes a try ...
int i = 0;

static void c() __attribute__((constructor));

static void c() {
  i = 42;
}
... -export-dynamic to build a shared library and now ...

extern int i;
main() {
  printf( "%d\n", i );
}
... link this to the library.


Cheers,
Juergen

-- 
\ Real name     : Jürgen Heinzl                 \       no flames      /
 \ EMail Private : juergen@monocerus.demon.co.uk \ send money instead /


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]